检查Android设备是否已启用“访问我的位置”权限

18

我有一个使用位置功能的安卓应用程序。但是我注意到如果用户在“设置”>“位置访问”中禁用了“访问我的位置”,那么什么都不起作用了。如何检查它是否已启用?

如果被禁用,如何从我的应用程序打开这些设置?

谢谢

已解决:

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

8
您可以这样检查:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // Return a boolean

编辑:

如果您想检查网络提供商:

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

编辑2:

如果您想打开设置,可以使用以下意图:

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

你也可以检查网络提供商的可用性(将 LocationManager.GPS_PROVIDER 替换为 LocationManager.NETWORK_PROVIDER)。 - Brtle
1
如果您想使用Wifi,请使用NETWORK提供程序。请查看文档和官方的Android文章,例如:http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html(请注意,现在还有更新的内容,通过Google Play服务,例如融合提供程序:https://developer.android.com/google/play-services/location.html)。 - Charlie Collins
Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED) 的效果更好,因为它提供了所有可用的位置提供程序。 - Romain Pellerin
谢谢Charlie Collings,我会查看融合提供者。 - Romain Pellerin
1
我从未使用过Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);,但我会尝试一下。另外,我提供了一个提示来打开位置源设置。 - Brtle

3

好的,看起来是Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 谢谢,你有任何想法如何从我的应用程序中打开它吗? - Romain Pellerin

2

另一种不使用Settings.Secure且无需扫描所有位置提供程序的方法是执行以下操作:

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
} 

0

不幸的是,自API 19起,使用Settings.Secure.LOCATION_PROVIDERS_ALLOWED已被弃用。

现在可以采用以下新方法:

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
}

-1

有两种方法来检查位置, 1-使用GPS 2-使用网络供应商 最好检查两个服务是否都已启用。为此,请使用此方法:)

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;
    }
}

1
我不知道为什么有人给我-1分...这个解决方案对我有效,我正在使用它。如果这个解决方案对你无效,请尝试另一个解决方案,不要标记为-1分的白痴。 - Ashana.Jackol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接