ActivityCompat.requestPermissions targetSdkVersion 30 不工作

ActivityCompat.requestPermissions for targetSdkVersion 30 is not working

我有以下权限:

private static final String[] LOCATION_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
};

我尝试使用以下行在我的代码中请求权限(activity 是我当前的 activity ref):

ActivityCompat.requestPermissions(activity, LOCATION_PERMISSIONS, 1);

如果我的 build.gradle 文件中有 targetSdkVersion 29 或更低版本,一切正常。出现权限对话框,我可以按下其中的按钮来授予权限。一切都很好

但是!在我将目标 sdk 更改为 Android 11: targetSdkVersion 30 后,此功能停止工作。 权限系统对话框未出现 - 我无法为我的应用授予位置权限。

所以有人可以帮助我吗?我错了什么? 我应该在我的代码中更改什么 - 才能正确使用 Android 11?

现在 targetSdkVersion 29 我也可以在 android 11 模拟器下 运行 我的应用程序。可能我根本不应该将目标 sdk 版本增加到:30?


解决方法是:

第 1 步:应用应请求前台位置权限:

private static final String[] FOREGROUND_LOCATION_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,       // GPS
            Manifest.permission.ACCESS_COARSE_LOCATION,     // GPS approximate location
    };

第 2 步:应用应请求后台位置权限:

@RequiresApi(api = Build.VERSION_CODES.Q)
    private static final String[] BACKGROUND_LOCATION_PERMISSIONS = {
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
    };    

仅此顺序!

ActivityCompat.requestPermissions(activity, FOREGROUND_LOCATION_PERMISSIONS, 1);
// Check the first statement grant needed permissions, and then run the second line:
ActivityCompat.requestPermissions(activity, BACKGROUND_LOCATION_PERMISSIONS, 1);

如果我首先尝试请求后台权限 - 它不会工作。

如果我只请求后台权限(没有已经授予的前台权限)- 它不会工作。

我应该申请前台权限 - 然后我应该申请后台权限 - 一个接一个。

在 android 如果用户没有首先授予前台位置权限,则 11 次后台位置权限请求将被隐式拒绝。

同时包含前台和后台位置权限的请求被视为无效:

If your app targets Android 11 (API level 30) or higher, the system enforces this best practice. If you request a foreground location permission and the background location permission at the same time, the system ignores the request and doesn't grant your app either permission.

Request location access at runtime