3

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?

3 Answers3

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