首页 > 解决方案 > 检查全球位置访问权限

问题描述

在 Android 中,我可以检查我的应用是否具有 Manifest 要求的位置权限,如下所示:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  // show alert
}

但是,当用户转到“Android 设置”>“安全和隐私”>“位置访问”并将其全局关闭时,该警报不会显示。有没有办法检测该全局权限是否设置为关闭?

标签: androidpermissionslocation

解决方案


如果启用了全局位置,则此函数返回

   public boolean isLocationEnabled() {
       int locationMode = Settings.Secure.LOCATION_MODE_OFF;
       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_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

推荐阅读