Runtime Permission Control in Android 6.0

I wrote a piece of code, but it doesn't work properly anyway:

File dir = Environment.getExternalStorageDirectory();
...
File[] children = dir.listFiles(); // children are taken out as null

Then I added a judgment and found that dir was unreadable:

File dir = Environment.getExternalStorageDirectory();
...
if (dir.canRead()) { // dir is not readable
    File[] children = dir.listFiles();    ...
}

Don't you have permission to register in manifest? No, obviously there is WRITE_EXTERNAL_STORAGE...

 

Then I gave up thinking and played a game, and came back and figured it out - this machine is Android 6.0, in addition to the manifest permission, there is also a runtime permission ( Requesting Permissions at Run Time ) . // Playing the game is really refreshing

 

Speak directly with code:

1. Check whether the corresponding permissions have been granted:

int result = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); // This is the method of Context

Note that result is an int and takes values ​​from PackageManager.PERMISSION_GRANTED and PackageManager.PERMISSION_DENIED.

 

2. If permission is not obtained, apply for permission:

final String[] permissionsToRequest = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
final int requestCode = 0;
requestPermissions(permissionsToRequest, requestCode); // This is the method of Activity

After the above code is executed, the system will pop up a Dialog, prompting the user to view the permission application.

 

3. After the user operation is completed, the following Activity methods will be called back:

public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults)

In it, it can be processed for the requestCode.

 

4. Supplement:

The official document recommends that before applying for permissions, consider whether it is necessary to apply for permissions and explain to the user (for example, this game is for Mao to read your contacts). At the same time, Activity provides a prototype of this interface:

public boolean shouldShowRequestPermissionRationale (String permission)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326893681&siteId=291194637