Android 6.0 multiple permissions

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

    This is what I have done in my activity. Hoping will be helpful. I am asking for camera and microphone permissions.

    public class ActiveCallActivity extends AppCompatActivity {
        .....
    
        private static final String cameraPermissionKey = "cameraPermission";
        private static final String microphonePermissionkey = "microphonePermission";
    
        private static ArrayList<String> permissionsQueue = new ArrayList<String>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            .....
            // in ValidationCheckersAndValidators simply checking if have permission or not.
            if(ValidationCheckersAndValidators.haveCameraPermission(this)) performHaveCameraPermissionLayout(); else performHaveNoCameraPermissionLayout();
            if(ValidationCheckersAndValidators.haveMicrophonePermission(this)) performHaveMicrophonePermissionLayout(); else performHaveNoMicrophonePermissionLayout();
    
        }
    
        private void performHaveNoCameraPermissionLayout() {
            .....
            permissionsQueue.add(cameraPermissionKey);
        }
    
        private void performHaveNoMicrophonePermissionLayout() {
            .....
            permissionsQueue.add(microphonePermissionkey);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
    
            .....
            passThroughPermissionsQueue();
        }
    
        private void passThroughPermissionsQueue() {
            if(!permissionsQueue.isEmpty()) {
                String permissionKey = permissionsQueue.remove(0);
                switch (permissionKey) {
                    case cameraPermissionKey: {
                        ValidationCheckersAndValidators.requestForCameraPermission(this);
                        return;
                    }
                    case microphonePermissionkey: {
                        ValidationCheckersAndValidators.requestForMicrophonePermission(this);
                        return;
                    }
                }
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            switch(requestCode) {
                case cameraPermissionRequestCode: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        performHaveCameraPermissionLayout();
                    }
                    break;
                }
                case microphonePermissionRequestCode: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        performHaveMicrophonePermissionLayout();
                    }
                    break;
                }
            }
            passThroughPermissionsQueue();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:41

    My handler class for request multiple permissions. You can check the full using here

    public class RequestPermissionHandler {
        private Activity mActivity;
        private RequestPermissionListener mRequestPermissionListener;
        private int mRequestCode;
    
        public void requestPermission(Activity activity, @NonNull String[] permissions, int requestCode,
                RequestPermissionListener listener) {
            mActivity = activity;
            mRequestCode = requestCode;
            mRequestPermissionListener = listener;
    
            if (!needRequestRuntimePermissions()) {
                mRequestPermissionListener.onSuccess();
                return;
            }
            requestUnGrantedPermissions(permissions, requestCode);
        }
    
        private boolean needRequestRuntimePermissions() {
            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
        }
    
        private void requestUnGrantedPermissions(String[] permissions, int requestCode) {
            String[] unGrantedPermissions = findUnGrantedPermissions(permissions);
            if (unGrantedPermissions.length == 0) {
                mRequestPermissionListener.onSuccess();
                return;
            }
            ActivityCompat.requestPermissions(mActivity, unGrantedPermissions, requestCode);
        }
    
        private boolean isPermissionGranted(String permission) {
            return ActivityCompat.checkSelfPermission(mActivity, permission)
                    == PackageManager.PERMISSION_GRANTED;
        }
    
        private String[] findUnGrantedPermissions(String[] permissions) {
            List<String> unGrantedPermissionList = new ArrayList<>();
            for (String permission : permissions) {
                if (!isPermissionGranted(permission)) {
                    unGrantedPermissionList.add(permission);
                }
            }
            return unGrantedPermissionList.toArray(new String[0]);
        }
    
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                @NonNull int[] grantResults) {
            if (requestCode == mRequestCode) {
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            mRequestPermissionListener.onFailed();
                            return;
                        }
                    }
                    mRequestPermissionListener.onSuccess();
                } else {
                    mRequestPermissionListener.onFailed();
                }
            }
        }
    
        public interface RequestPermissionListener {
            void onSuccess();
    
            void onFailed();
        }
    }
    

    0 讨论(0)
  • 2020-11-22 04:41

    Use helper like this (permissions names do not matter).

    public class MyPermission {
    
    private static final int PERMISSION_REQUEST_ALL = 127;
    private MainActivity mMainActivity;
    
    MyPermission(MainActivity mainActivity) {
        mMainActivity = mainActivity;
    }
    
    public static boolean hasPermission(String permission, Context context) {
        if (isNewPermissionModel()) {
            return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
        }
        return true;
    }
    
    private static boolean hasPermissions(Context context, String... permissions) {
        if (isNewPermissionModel() && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    
    private static boolean shouldShowRationale(Activity activity, String permission) {
        return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
    }
    
    private static boolean isNewPermissionModel() {
        return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1;
    }
    
    
    /**
     * check all permissions
     */
    void checkAll() {
        //check dangerous permissions, make request if need (Android will ask only for the ones it needs)
        String[] PERMISSIONS = {
                permission.READ_CALENDAR,           
                permission.ACCESS_COARSE_LOCATION   
        };
    
        if (!hasPermissions(mMainActivity, PERMISSIONS)) {
            ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL);
        }
    }
    
    void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_ALL) {
            if (grantResults.length > 0) {
                //for not granted
                for (int i = 0; i < permissions.length; i++) {
    
                    if (permissions[i].equals(permission.READ_CALENDAR)) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar);
                        }
                    } else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location);
                        }
                    }
    
                }
            }
        }
    }
    
    private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) {
        if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false.
    
            //Show an explanation to the user with action
            mMainActivity.mSnackProgressBarManager.show(
                    new SnackProgressBar(
                            SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog)
                    )
                            .setAction("OK", new OnActionClickListener() {
                                @Override
                                public void onActionClick() {
                                    checkAll();
                                }
                            })
                            .setSwipeToDismiss(true).setAllowUserInput(true)
                    , MainActivity.SNACKBAR_WARNING_DURATION
            );
    
        } // else do nothing
    }
    

    }

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题