导入的依赖:
//RxPermissions 权限管理
implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.3@aar'
//RxJava2
implementation 'io.reactivex.rxjava2:rxjava:2.0.0'
使用方式
RxPermissions rxPermission = new RxPermissions(this);
rxPermission
.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
// Manifest.permission.ACCESS_NETWORK_STATE,
// Manifest.permission.ACCESS_WIFI_STATE,
// Manifest.permission.READ_PHONE_STATE,
// Manifest.permission.REQUEST_INSTALL_PACKAGES
)
.subscribe(new Consumer<Permission>() {
@Override
public void accept(Permission permission) throws Exception {
if (permission.granted) {
// 用户已经同意该权限
LogUtil.d(permission.name + " is granted.");
} else if (permission.shouldShowRequestPermissionRationale) {
// 用户拒绝了该权限,没有选中『不再询问』(Never ask again),那么下次再次启动时,还会提示请求权限的对话框
LogUtil.d( permission.name + " is denied. More info should be provided.");
} else {
// 用户拒绝了该权限,并且选中『不再询问』
LogUtil.d( permission.name + " is denied.");
//TODO
}
}
});
注意事项(测试很久才发现到的):
不管是否申请过权限都会调用里面的方法会遮挡activity,使activity调用一次onResume和onPause,RxPermissions发现已有权限后不会弹出申请对话框,activity还会调用一次onResume方法,造成多次调用
解决方法:
在使用之前先判断是否已有权限,若有则跳过,若无则申请
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
RxPermissions rxPermission = new RxPermissions(this);
rxPermission
.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
// Manifest.permission.ACCESS_NETWORK_STATE,
// Manifest.permission.ACCESS_WIFI_STATE,
// Manifest.permission.READ_PHONE_STATE,
// Manifest.permission.REQUEST_INSTALL_PACKAGES
)
.subscribe(new Consumer<Permission>() {
@Override
public void accept(Permission permission) throws Exception {
if (permission.granted) {
// 用户已经同意该权限
LogUtil.d(permission.name + " is granted.");
} else if (permission.shouldShowRequestPermissionRationale) {
// 用户拒绝了该权限,没有选中『不再询问』(Never ask again),那么下次再次启动时,还会提示请求权限的对话框
LogUtil.d( permission.name + " is denied. More info should be provided.");
} else {
// 用户拒绝了该权限,并且选中『不再询问』
LogUtil.d( permission.name + " is denied.");
//TODO
}
}
});
}
}
后记:测试发现使用 AndPermission没有这样的问题
网友评论