Android code application permission (for Android6.0 or above)

IF (ContextCompat.checkSelfPermission (the this, 
                Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                ! = PERMISSION_GRANTED) {// if the judge has given permission 
            IF (ActivityCompat.shouldShowRequestPermissionRationale (the this, 
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 
                // Here you can write a dialog Items such as this explain to the user why they should apply for permission, and then apply for permission again in the confirmation key of the dialog box. It returns false 

            if the user selects "no longer ask" } else { 
                // Apply permission, within the string array Is one or more permissions to apply for, 1 is the return parameter of the application permission result, you can learn the application result in onRequestPermissionsResult 
                ActivityCompat.requestPermissions (this, 
                        new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE, 
rewrite onRequestPermissionsResult 
{ 
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}}

if (requestCode == 1) {// requestCode value is 1 
            for (int i = 0; i <permissions.length; i ++) { 
                if (grantResults [i] == PERMISSION_GRANTED) { 
                    Toast.makeText (this, "" + "Permission" + permissions [i] + "application successful", Toast.LENGTH_SHORT) .show (); 
                } else { 
                    Toast.makeText (this, "" + "permission" + permissions [i] + "application failed ", Toast.LENGTH_SHORT) .show (); 
                } 
            } 
        } 
}

  

Activity in the host 
@Override 
public  void onRequestPermissionsResult ( int requestCode, @NonNull String [] Permissions, @NonNull int [] grantResults) 
  { 
       Super .onRequestPermissionsResult (requestCode, Permissions, grantResults);
        // acquired under Fragment Activity 
       List <Fragment> fragments = getSupportFragmentManager (). getFragments ();
        if (fragments == null ) 
       { 
           return ; 
       } 
       // Find the onRequestPermissionsResult method in Fragment and call 
       for (Fragment fragment: fragments) 
       { 
           if(fragment! = null ) 
           { 
               // The onRequestPermissionsResult method in our Fragment will be called here 
               fragment.onRequestPermissionsResult (requestCode, permissions, grantResults); 
           } 
       } 
   }

 2. Fragment only request permission in the following way 

fragment.requestPermissions (mPermissionList, REQUEST_CODE_CAMERA ) 
Instead of ActivityCompat / ContextCompat 

ActivityCompat.requestPermissions ((AppCompatActivity) context, new String [] {Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE)

 

Guess you like

Origin www.cnblogs.com/matd/p/12734879.html