Android | Location Settings Dialog

Datetime:2016-08-22 23:23:09          Topic: Andrew Development           Share

In a previous post Android | Check & Enable Location Service , we have seen how to check if the location service is enabled and how to redirect the user to the settings screen where he can enable the location service if it is disabled. Google Play Service 7.0 has introduced a new standard mechanism to check if the necessary location settings are enabled or not. Your app can display a location settings dialog for the user to change their settings without leaving your app.

Show Location Settings Dialog if Location Settings is not Enabled

  • The two important methods are checkLocationSettings() and onResult()
public class MainActivity extends Activity implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener,
        ResultCallback<LocationSettingsResult> {




protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;


         /* Check checkLocationSettings and handle callback
   * ***************************
   *  1. checkLocationSettings
   *  2. @Override ResultCallback.onResult()  
   ***************************** */
        protected void checkLocationSettings() {
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(
                        mGoogleApiClient,
                        mLocationSettingsRequest
                );

        result.setResultCallback(this);
        }


        @Override
        public void onResult(LocationSettingsResult locationSettingsResult) {
         final Status status = locationSettingsResult.getStatus();
         switch (status.getStatusCode()) {
          case LocationSettingsStatusCodes.SUCCESS:

                // NO need to show the dialog;

                break;

            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
              //  Location settings are not satisfied. Show the user a dialog

                try {
                    // Show the dialog by calling startResolutionForResult(), and check the result
                    // in onActivityResult().

                    status.startResolutionForResult((Activity)context, REQUEST_CHECK_SETTINGS);

                } catch (IntentSender.SendIntentException e) {
                  
                      //unable to execute request
                }
                break;

            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are inadequate, and cannot be fixed here. Dialog not created
                break;
        }
     }

}

Complete Source Code @ GitHub





About List