How to know in android if location is turned off b

2019-08-27 11:50发布

问题:

This question already has an answer here:

  • android check if user turned off location 3 answers

How can I identify that if the location turned off by the user in android? I also want to show a dialog to go to settings.

回答1:

public static boolean canGetLocation() {
    return isLocationEnabled(App.appInstance); // application context
}

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return locationMode != Settings.Secure.LOCATION_MODE_OFF;
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        return !TextUtils.isEmpty(locationProviders);
    }
}

This is a quick tool to check if device location is enabled or not, Hope this helps.

This will return a boolean indicating enabled or not.

And you can navigate not location settings by using the following intent from the alert dialog click listener,

startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));


回答2:

You can trigger a broadcast receiver to know the gps is turned on/ off.

answer is here : How to trigger broadcast receiver when gps is turn on/off?

to check if gps is on or off : How to check if GPS is Disabled Android