第一种方式:引入三方库,利用第三方申请权限
1.引入三方库:
api'com.tbruyelle.rxpermissions2:rxpermissions:0.9.3@aar'
2.调用(当然你需要什么权限就申请什么权限)
private void requestPermissions() {
RxPermissions rxPermission =new RxPermissions(MainActivity.this);
rxPermission
.requestEach(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_CALENDAR,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_CONTACTS,
Manifest.permission.CAMERA
)
.subscribe(new Consumer() {
@Override
public void accept(Permission permission)throws Exception {
if (permission.granted) {
// 用户已经同意该权限
Log.d(TAG, permission.name +" is granted.");
}else if (permission.shouldShowRequestPermissionRationale) {
// 用户拒绝了该权限,没有选中『不再询问』(Never ask again),那么下次再次启动时,还会提示请求权限的对话框
Log.d(TAG, permission.name +" is denied. More info should be provided.");
}else {
// 用户拒绝了该权限,并且选中『不再询问』
Log.d(TAG, permission.name +" is denied.");
}
}
});
}
第二种方式自己申请权限,代码如下
1.先定义你需要申请的权限数组
private static final int REQUEST_EXTERNAL_STORAGE =1;
private static String[]PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_PHONE_STATE"};
2.开始申请权限(6.0以上需要动态)
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
//检测是否有写的权限
int permission = ActivityCompat.checkSelfPermission(this,
"android.permission.READ_PHONE_STATE");
if (permission != PackageManager.PERMISSION_GRANTED) {
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
3.处理权限回调方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
// 授权被允许
if (grantResults.length >0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("-------->", "授权请求被允许");
}else {
Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
finish();
Log.e("-------->", "授权请求被拒绝");
}
}
}
}
网友评论