Skip to content Skip to sidebar Skip to footer

Check If 'access To My Location' Is Enabled - Android

I have an android app that uses location. But I noticed that if users disable the 'Access to my location' in Settings > Location access, nothing works anymore. How can I check t

Solution 1:

You can check it like that:

LocationManagerlocationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // Return a boolean

EDIT:

If you want to check the network provider:

LocationManagerlocationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) // Return a boolean

EDIT 2:

If you want to open the settings, you can use this intent:

Intentintent=newIntent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);

Solution 2:

Solution 3:

An alternative way to do that without using Settings.Secure and without scanning all location providers would be to do:

LocationManagerlocationManager= (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
intprovidersCount= locationManager.getProviders(true).size(); // Listing enabled providers onlyif (providersCount == 0) {
    // No location providers at all, location is off
} 

Solution 4:

Unfortunately, it seems the using of Settings.Secure.LOCATION_PROVIDERS_ALLOWED is deprecated since API 19.

A new way to do that would be:

int locationMode = Settings.Secure.getInt(
    getContentResolver(),
    Settings.Secure.LOCATION_MODE,
    Settings.Secure.LOCATION_MODE_OFF // Default value if not found
);

if (locationMode == Settings.Secure.LOCATION_MODE_OFF) {
    // Location is off
}

Solution 5:

There are two ways to check location, 1-using GPS 2-using network provider its better to check both service are enabled or not.For that use this method :)

publicbooleancheckServices(){
    //check location serviceLocationManagerlocationManager= (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            returntrue;
    }
}

Post a Comment for "Check If 'access To My Location' Is Enabled - Android"