object PermissionsUtil {
enum class PermissionType {
EXTERNAL_STORAGE,//存储读写
CAMERA,//相机
}
/**
* @param rxPermissions RxPermissions对象
* @param success 成功的操作
* @param error 失败的操作
* @param types PermissionType 需要的权限
*/
fun requestPermissions(
rxPermissions: RxPermissions,
success: () -> Unit,
error: () -> Unit,
vararg types: PermissionType
) {
getPermissions(rxPermissions, *types)
.subscribe(object : Observer<Boolean> {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: Boolean) {
if (t) {
success()
} else {
error()
}
}
override fun onError(e: Throwable) {
error()
}
})
}
private fun getPermissions(
rxPermissions: RxPermissions,
vararg types: PermissionType
): Observable<Boolean> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && types.isNotEmpty()) {
val list = mutableListOf<String>()
types.forEach {
when (it) {
PermissionsUtil.PermissionType.EXTERNAL_STORAGE -> {
list.add(Manifest.permission.READ_EXTERNAL_STORAGE)
list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
PermissionsUtil.PermissionType.CAMERA -> {
list.add(Manifest.permission.CAMERA)
}
}
}
val array = list.toTypedArray()
rxPermissions.request(*array)
} else {
Observable.create { emitter ->
emitter.onNext(true)
emitter.onComplete()
}
}
}
}
使用
PermissionsUtil.requestPermissions(
RxPermissions(this),
{ download() },
{ showShortToast(R.string.err_nopermission) },
PermissionsUtil.PermissionType.EXTERNAL_STORAGE
)
网友评论