Android M动态权限管理

时间:2022-01-07 05:21:14

Android M动态权限管理。下面是google对Android6.0以上的运行时检查权限的部分说明:

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app's Settings screen.

Android M动态权限管理


在Activity中的onCreate调用handleAfterPermission()权限进行处理就可以了。

public static final int REQUEST_PERMISSION_CODE = 100;
private void checkInitPermissions(){

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = new String[]{
//放入需要授予的权限,例如需要写入的权限
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
if (ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])){
ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION_CODE);
}else{
ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION_CODE);
}
}
} else {
handleAfterPermissions();
}
}

private void handleAfterPermissions(){
FileUtil.initAppDir();
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE){
handleAfterPermissions();
}
}