美文网首页安卓
基于RxPermissions和RxJava封装的权限申请工具类

基于RxPermissions和RxJava封装的权限申请工具类

作者: 远在远方的风yzyfdf | 来源:发表于2020-03-26 10:56 被阅读0次
    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
            )
    

    相关文章

      网友评论

        本文标题:基于RxPermissions和RxJava封装的权限申请工具类

        本文链接:https://www.haomeiwen.com/subject/ysvquhtx.html