android 动态权限管理

在主activity中写回调
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: //Toast.makeText(this, "权限", Toast.LENGTH_SHORT).show(); break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); break; } }
单独写一个方法
`public class PermissionApply {
Context context;

public PermissionApply(Context context) {
    this.context = context;

}
//在SD卡中创建与删除文件权限
String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//没有申请到的权限
List<String> mPermissionList = new ArrayList<>();
// 检查权限
public void checkPermission() {
    mPermissionList.clear();
    //判断哪些权限未授予
    for (int i = 0; i < permissions.length; i++) {
        if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
            mPermissionList.add(permissions[i]);
        }
    }
    /**
     * 判断是否为空
     */
    if (mPermissionList.isEmpty()) {//未授予的权限为空,表示都授予了

    } else {//请求权限方法
        String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
        ActivityCompat.requestPermissions((Activity) context, permissions, 1);
    }
}

}
`

posted @ 2021-11-19 18:07  九块  阅读(151)  评论(0编辑  收藏  举报