Android 6.0 multiple permissions

后端 未结 22 2365
太阳男子
太阳男子 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:42

    There is nothing wrong with answers asking for multiple permissions but multiple permission result code is not implemented very elegantly and may cause checking wrong permission result.

    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) is terrible logic for checking multiple permissions result, i don't know why Google implemented such a terrible code.

    It's a mess especially when you check multiple permissions. Let say you ask for CAMERA, ACCESS_FINE_LOCATION and ACCESS_NETWORK_STATE.

    You need to check for ACCESS_FINE_LOCATION but user only granted CAMERA at first run and you check for grantResults[1] but in second run ACCESS_FINE_LOCATION becomes the permission with index 0. I got so many problems with user not granting all permissions at once and have to write so pointless permission result logic.

    You should either use

       int size = permissions.length;
        boolean locationPermissionGranted = false;
    
        for (int i = 0; i < size; i++) {
            if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)
                    && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                locationPermissionGranted = true;
            }
        }
    

    Or simpler one

       if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
               // Do something ...
            }
    

    in onPermissionRequestResult method.

提交回复
热议问题