How to ask user to turn on location

前端 未结 2 838
遥遥无期
遥遥无期 2021-01-23 04:46

How can I prompt the user to turn on the gps in this way in below image. I tried using the alert dialog method but it takes to the settings view I wanted gps to be turned on wit

2条回答
  •  后悔当初
    2021-01-23 05:23

    This works in java AndroidX 2020 updated:

    private void enableLoc() {
    
    
    
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
    
    
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
    
        builder.setAlwaysShow(true);
    
        Task result =
                LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
    
        result.addOnCompleteListener(new OnCompleteListener() {
    
    
            @Override
            public void onComplete(Task task) {
                try {
                    LocationSettingsResponse response = task.getResult(ApiException.class);
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
    
                } catch (ApiException exception) {
                    switch (exception.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the
                            // user a dialog.
                            try {
                                // Cast to a resolvable exception.
                                ResolvableApiException resolvable = (ResolvableApiException) exception;
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                resolvable.startResolutionForResult(
                                        Maps.this,
                                        LOCATION_SETTINGS_REQUEST);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            } catch (ClassCastException e) {
                                // Ignore, should be an impossible error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.
                            break;
                    }
                }
            }
        });
    
    }
    

提交回复
热议问题