Check if 'Access to my location' is enabled - Android

左心房为你撑大大i 提交于 2019-12-20 09:57:09

问题


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 that it's enabled? In case it's disabled, how to open those settings from my app?

Thanks

SOLVED :

String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (locationProviders == null || locationProviders.equals("")) {
    ...
    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}

回答1:


may be this will be useful check this site it discusses about location service

http://www.scotthelme.co.uk/android-location-services/




回答2:


You can check it like that:

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

EDIT:

If you want to check the network provider:

LocationManager locationManager = (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:

Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);



回答3:


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

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



回答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
}



回答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 :)

public boolean checkServices(){
    //check location service
    LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            return true;
    }
}


来源:https://stackoverflow.com/questions/18150613/check-if-access-to-my-location-is-enabled-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!