Android 6.0 multiple permissions

后端 未结 22 2216
太阳男子
太阳男子 2020-11-22 03:58

I know that Android 6.0 has new permissions and I know I can call them with something like this

if (ContextCompat.checkSelfPermission(this, Manifest.permiss         


        
22条回答
  •  执念已碎
    2020-11-22 04:24

    Just include all 4 permissions in the ActivityCompat.requestPermissions(...) call and Android will automatically page them together like you mentioned.

    I have a helper method to check multiple permissions and see if any of them are not granted.

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    

    Or in Kotlin:

    fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
        ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }
    

    Then just send it all of the permissions. Android will ask only for the ones it needs.

    // The request code used in ActivityCompat.requestPermissions()
    // and returned in the Activity's onRequestPermissionsResult()
    int PERMISSION_ALL = 1; 
    String[] PERMISSIONS = {
      android.Manifest.permission.READ_CONTACTS, 
      android.Manifest.permission.WRITE_CONTACTS, 
      android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
      android.Manifest.permission.READ_SMS, 
      android.Manifest.permission.CAMERA
    };
    
    if (!hasPermissions(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }
    

提交回复
热议问题