Follow the steps mentioned below
1) Create a LocationRequest
as per your wish
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
2) Create a LocationSettingsRequest.Builder
LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
settingsBuilder.setAlwaysShow(true);
3) Get LocationSettingsResponse
Task
using following code
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(settingsBuilder.build());
Note: LocationServices.SettingsApi
is deprecated so, use SettingsClient
Instead.
4) Add a OnCompleteListener
to get the result from the Task.When the Task
completes, the client can check the location settings by looking at the status code from the LocationSettingsResponse
object.
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(MapsActivity.this,
LOCATION_SETTINGS_REQUEST);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
CASE 1: LocationSettingsStatusCodes.RESOLUTION_REQUIRED
: Location is not enabled but, we can ask the user to enable the location by prompting him to turn on the location with the dialog (by calling startResolutionForResult
).
CASE 2: 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.
5) OnActivityResult
we can get the user action in the location settings dialog. RESULT_OK
=> User turned on the Location. RESULT_CANCELLED
- User declined the location setting request.