When to request permission at runtime for Android Marshmallow 6.0?

后端 未结 11 1014
故里飘歌
故里飘歌 2020-12-06 05:54

I am testing my app on Marshmallow 6.0 and it\'s getting force closed for the android.permission.READ_EXTERNAL_STORAGE, even if it is defined in th

11条回答
  •  日久生厌
    2020-12-06 06:29

    This is worked for me !!! In Your Splash Activity of your application do the following,

    1) Declare an int variable for request code,

    private static final int REQUEST_CODE_PERMISSION = 2;

    2) Declare a string array with the number of permissions you need,

     String[] mPermission = {Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS,
     Manifest.permission.ACCESS_FINE_LOCATION,
     Manifest.permission.WRITE_EXTERNAL_STORAGE};
    

    3) Next Check the condition for runtime permission on your onCreate method,

    try {
                if (ActivityCompat.checkSelfPermission(this, mPermission[0])
                        != MockPackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(this, mPermission[1])
                                != MockPackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(this, mPermission[2])
                                != MockPackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(this, mPermission[3])
                                != MockPackageManager.PERMISSION_GRANTED) {
    
                    ActivityCompat.requestPermissions(this,
                            mPermission, REQUEST_CODE_PERMISSION);
    
                  // If any permission aboe not allowed by user, this condition will execute every tim, else your else part will work
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    4) Now Declare onRequestPermissionsResult method to check the request code,

    @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            Log.e("Req Code", "" + requestCode);
            if (requestCode == REQUEST_CODE_PERMISSION) {
                if (grantResults.length == 4 &&
                        grantResults[0] == MockPackageManager.PERMISSION_GRANTED &&
                        grantResults[1] == MockPackageManager.PERMISSION_GRANTED &&
                        grantResults[2] == MockPackageManager.PERMISSION_GRANTED &&
                        grantResults[3] == MockPackageManager.PERMISSION_GRANTED) {
    
                   // Success Stuff here
    
                }
            }
    
        }
    

提交回复
热议问题