Android 6.0 multiple permissions

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

    I have successfully implemented simple code for Multiple permission at Once. Follow the below steps 1:Make Utility.java class like below

    public class Utility {
    public static final int MY_PERMISSIONS_REQUEST = 123;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean checkPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST);
                    } else {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,Manifest.permission.GET_ACCOUNTS}, MY_PERMISSIONS_REQUEST);
                    }
                    return false;
                }
            }
        }
        return true;
    }
    }
    

    2: Now call

    boolean permissionCheck = Utility.checkPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.GET_ACCOUNTS);  
    

    in your Activity onCreate() or according to your logic.

    3:Now check permission before performing operation for particular task

    if (permissionCheck) {
     performTaskOperation();//this method what you need to perform
    } else {
            Toast.makeText(this, "Need permission ON.", Toast.LENGTH_SHORT).show();
           }
    

    4: Now implement onRequestPermissionsResult() method in your Activity as below

      @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (userChoosenTask.equals("STORAGE"))
                        performTaskOperation();//this method what you need to perform
                }
                break;
        }
    }
    

提交回复
热议问题