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?
Asked
Active
Viewed 3,892 times
3
-
1This is your answer : http://stackoverflow.com/a/33408809/1281180 – blackkara Apr 17 '16 at 23:30
-
Possible duplicate of http://stackoverflow.com/questions/3470693/android-get-location-or-prompt-to-enable-location-service-if-disabled – abielita Apr 18 '16 at 07:08
3 Answers
7
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();
}

Siddarth Nyati
- 141
- 3
- 5
0
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).

Maxim G
- 1,479
- 1
- 15
- 23
0
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))
}
}

The Hungry Androider
- 2,274
- 5
- 27
- 52