How To Ask User To Enable Gps At The Launch Of Application?
Solution 1:
If you want something as shown in below image, follow along.
Add the following dependencies in your app
build.gradle
implementation 'com.google.android.gms:play-services-location:16.0.0'
Create the type of location request you want, we want high accuracy for GPS
LocationRequestlocationRequest= LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builderbuilder=newLocationSettingsRequest.Builder() .addLocationRequest(locationRequest);
Now we need to check current state of GPS. For this, we have to use
LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build())
This will return aTask
which needs to handled asynchronously. In RESOLUTION_REQUIRED case, we ask user to give permissions, this is where we show the user prompt to enable GPS.Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build()); result.addOnCompleteListener(newOnCompleteListener<LocationSettingsResponse>() { @OverridepublicvoidonComplete(@NonNull Task<LocationSettingsResponse> task) { try { LocationSettingsResponseresponse= 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.ResolvableApiExceptionresolvable= (ResolvableApiException) exception; // Show the dialog by calling startResolutionForResult(),// and check the result in onActivityResult(). resolvable.startResolutionForResult( getActivity(), LocationRequest.PRIORITY_HIGH_ACCURACY); } 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; } } } });
Now that we have asked user to turn on GPS, we need to check whether user allowed it or ignored it. For this, override onActivityResult. Please note that, if you're implementing above code in a fragment, result will be received in the enclosing Activity. So override onActivityResult in the Activity class.
@OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case LocationRequest.PRIORITY_HIGH_ACCURACY: switch (resultCode) { case Activity.RESULT_OK: // All required changes were successfully made Log.i(TAG, "onActivityResult: GPS Enabled by user"); break; case Activity.RESULT_CANCELED: // The user was asked to change settings, but chose not to Log.i(TAG, "onActivityResult: User rejected GPS request"); break; default: break; } break; } }
Solution 2:
This is the kotlin implementation of @Ananth answer
privatefunshowLocationPrompt() {
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val result: Task<LocationSettingsResponse> = LocationServices.getSettingsClient(activity).checkLocationSettings(builder.build())
result.addOnCompleteListener { task ->
try {
val response = task.getResult(ApiException::class.java)
// All location settings are satisfied. The client can initialize location// requests here.
} catch (exception: ApiException) {
when (exception.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
try {
// Cast to a resolvable exception.val resolvable: ResolvableApiException = exception as ResolvableApiException
// Show the dialog by calling startResolutionForResult(),// and check the result in onActivityResult().
resolvable.startResolutionForResult(
activity, LocationRequest.PRIORITY_HIGH_ACCURACY
)
} catch (e: IntentSender.SendIntentException) {
// Ignore the error.
} catch (e: ClassCastException) {
// Ignore, should be an impossible error.
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
// Location settings are not satisfied. But could be fixed by showing the// user a dialog.// Location settings are not satisfied. However, we have no way to fix the// settings so we won't show the dialog.
}
}
}
}
}
overridefunonActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
LocationRequest.PRIORITY_HIGH_ACCURACY -> {
if (resultCode == Activity.RESULT_OK) {
Log.e("Status: ","On")
} else {
Log.e("Status: ","Off")
}
}
}
}
Solution 3:
use SettingsApi if you not want to force user to go settings page to enable gps. here the link of how to use SettingsApi SettingsApi
Solution 4:
Image of GPS permission like Google Maps
If you want to ask permission like shown in the above link, you can refer to my answer: https://stackoverflow.com/a/64757407/10618364
Code is written with GoogleApi and SettingsClient API, not with deprecated GoogleClientApi and SettingsApi.
It is also compatible with Android 11. ;)
Solution 5:
publicvoidshowSettingAlert()
{
AlertDialog.BuilderalertDialog=newAlertDialog.Builder(context);
alertDialog.setTitle("GPS setting!");
alertDialog.setMessage("GPS is not enabled, Do you want to go to settings menu? ");
alertDialog.setPositiveButton("Setting", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
Intentintent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
Post a Comment for "How To Ask User To Enable Gps At The Launch Of Application?"