'How to prompt user to turn on location?
I have an app where when we click a button the app launches the google map with a search query. But I need the location to be turned on to provide accurate results. Is it possible?
Solution 1:[1]
I understood your query here is a code which should be added on your onCreate method
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
Solution 2:[2]
You should add permission in your AndroidManifest.xml.
General information about Android permissions here.
Be aware for Android 6 permission mechanism changed (it became iOS like).
Solution 3:[3]
A more complete solution that checks all location providers:
private fun launchLocationServicePage(context: Context) {
val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
val providers = locationManager.getProviders(true)
if (providers.isEmpty()) {
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siddarth Nyati |
| Solution 2 | Maxim G |
| Solution 3 | The Hungry Androider |
