-->

How to enable Location access programmatically in

2019-01-16 17:04发布

问题:

I am working on map related android application and I need to check location access enable or not in client side development if location services is not enable show the dialog prompt.

How to enable "Location access" Programmatically in android?

回答1:

Use below code to check. If it is disabled, dialog box will be generated

public void statusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    }
}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}


回答2:

You can try these methods below:

To check if GPS and network provider is enabled:

public boolean canGetLocation() {
    boolean result = true;
    LocationManager lm;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    if (lm == null)

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // exceptions will be thrown if provider is not permitted.
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {

    }
    try {
        network_enabled = lm
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }
    if (gps_enabled == false || network_enabled == false) {
        result = false;
    } else {
        result = true;
    }

    return result;
}

Alert Dialog if the above code returns false:

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    // Setting Dialog Title
    alertDialog.setTitle("Error!");

    // Setting Dialog Message
    alertDialog.setMessage("Please ");

    // On pressing Settings button
    alertDialog.setPositiveButton(
            getResources().getString(R.string.button_ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                }
            });

    alertDialog.show();
}

How to use the two methods above:

if (canGetLocation() == true) {

    //DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED                 
} else {

    //SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS                                
    showSettingsAlert();

    }


回答3:

just checkout the following thread: How to check if Location Services are enabled? It provides a pretty good example of how to check whether the location service was enabled or not.



回答4:

LocationServices.SettingsApi is deprecated now, So We use SettingsClient

See Answer



回答5:

With recent Marshmallow update, even when the Location setting is turned on, your app will require to explicitly ask for permission. The recommended way to do this is to show the Permissions section of your app wherein the user can toggle the permission as required. The code snippet for doing this is as below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
    
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
} else {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean isGpsProviderEnabled, isNetworkProviderEnabled;
    isGpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if(!isGpsProviderEnabled && !isNetworkProviderEnabled) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Location Permission");
        builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(android.R.string.no, null);
        builder.show();
    }
}

And override the onRequestPermissionsResult method as below:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "coarse location permission granted");
            } else {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        }
    }
}

Another approach is you can also use the SettingsApi to inquire which location provider(s) are enabled. If none is enabled, you can prompt a dialog to change the setting from within the app.