简体   繁体   中英

How to declare permissions for different api level?

I am currently develop an android application that api levels between 21-29.My problem is some permissions are not supported below api level 29.For example <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> permission no need to declare below api level 29. When I define this permission and fetch all permissions then ask user to grant permission,application below api level 29 is crashing. I need to define different permissions for different api levels or how can i deal with this problem ?

Here is my manifest.xml

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.RECORD_AUDIO" />
  <uses-permission android:name="android.permission.CAMERA" />
  <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

and here is my code to get all permission

PackageInfo info =
       getPackageManager()
           .getPackageInfo(
               getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);

   ActivityCompat.requestPermissions(this, info.requestedPermissions, PERMISSION_CODE); 



@Override
   public void onRequestPermissionsResult(
       int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
     if (requestCode == PERMISSION_CODE) {

       OptionalInt minValuePermission = Arrays.stream(grantResults).min();

       if (minValuePermission.isPresent()
           && minValuePermission.getAsInt() == PackageManager.PERMISSION_GRANTED) {/**/}

you don't need to declare different lists for different OS versions - permission introduced later will be ommited/ignored on lower platforms

also: not all permissions can be acquired by ActivityCompat.requestPermissions , FOREGROUND_SERVICE isn't for shure (should be granted automatically) and you shouldn't ask for it. so you shouldn't obtain whole list of all declared permissions through PackageManager , instead make own Java/Kotlin array with runtime perms

ActivityCompat.requestPermissions(this,
                // below your array with runtime permissions
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                PERMISSION_CODE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM