问题
I have following permissions:
private static final String[] LOCATION_PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
I try to request permissions in my code with following line (activity is my current activity ref):
ActivityCompat.requestPermissions(activity, LOCATION_PERMISSIONS, 1);
Everything works fine if I have targetSdkVersion 29
or lower in my build.gradle file. Permissions dialog appear, I can press button in it to grant permissions. Everythig is fine
But! After I changed target sdk to Android 11: targetSdkVersion 30
this functionality stop working.
Permission system dialog doesn't appear - and I can't grant location permissions for my app.
So can anybody help me? What am I wrong? What should I change in my code - for correctly working with Android 11?
Now with targetSdkVersion 29
I can run my app under the android 11 emulator too. May be I shouldn't increment target sdk version to: 30 at all?
The solution is:
1 step. The app should request foreground location permissions :
private static final String[] FOREGROUND_LOCATION_PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION, // GPS
Manifest.permission.ACCESS_COARSE_LOCATION, // GPS approximate location
};
2 step. The app should request background location permissions :
@RequiresApi(api = Build.VERSION_CODES.Q)
private static final String[] BACKGROUND_LOCATION_PERMISSIONS = {
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
};
Only in this order!
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);
If I firstly trying to request background permission - it will not work.
If I request only background permissions (without already granted foreground permissions) - it will not work.
I should request foreground permissions - and then after that I should request background permission - one by one.
回答1:
On android 11 requests for background location permission will be implicitly denied if user haven't granted foreground location permission first.
Requests containing both foreground and background location permission at the same time are deemed invalid:
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.
See Request location access at runtime
来源:https://stackoverflow.com/questions/64388343/activitycompat-requestpermissions-for-targetsdkversion-30-is-not-working