在android6.0以上,有些权限申请仅仅在androidmanifest.xml里面静态申请是不够的,还需要动态申请.方法如下:
// 动态申请权限
private String[] mPermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE};
private void applyPermission() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//声明一个数组permissions,将需要的权限都放在里面
List<String> permissionList = new ArrayList<>();
int mRequestCode = 100;//权限请求码
//逐个判断权限是否已经通过
for (int i = 0; i < mPermissions.length; i++) {
if (ContextCompat.checkSelfPermission(this, mPermissions[i]) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(mPermissions[i]);//添加还未授予的权限
}
}
//申请未通过的权限权限
if (permissionList.size() > 0) {
ActivityCompat.requestPermissions(this, mPermissions, mRequestCode);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (grantResults.length > 0) {
Log.d(TAG, "grantResults.length:" + grantResults.length);
for (int i = 0 ;i < grantResults.length ; i ++){
if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
applyPermission();
break;
}
}
}
}
}
在你应用的启动界面的onCreate方法里面调用applyPermission方法就好了.
1.查询是否有未授予的权限
2.如果有,请求这些权限
3.请求结果判断是否有未授予的权限(在onRequestPermissionsResult里面),如果有再调applyPermission方法.
4.直到用户将所有权限都授予了.
方法简单粗暴.
网友评论