1. 程式人生 > >Android6.0動態許可權獲取框架:RxPermission(基於RxJava2)

Android6.0動態許可權獲取框架:RxPermission(基於RxJava2)

首先在build.gradle中新增依賴庫

rxjava和retrofit:

compile 'io.reactivex.rxjava2:rxjava:2.x.y'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

rxpermission:

compile 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.4@aar'

在需要動態獲取許可權的地方使用:

RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.requestEach(Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Permission>() {
                    @Override
public void accept(Permission permission) throws Exception { if (permission.granted) { // 使用者已經同意該許可權 toast("使用者已經同意該許可權"); } else if (permission.shouldShowRequestPermissionRationale) { // 使用者拒絕了該許可權,沒有選中『不再詢問』(Never ask again),那麼下次再次啟動時,還會提示請求許可權的對話方塊
toast("使用者拒絕了該許可權"); } else { // 使用者拒絕了該許可權,並且選中『不再詢問』,提醒使用者手動開啟許可權 toast("許可權被拒絕,請在設定裡面開啟相應許可權,若無相應許可權會影響使用"); } } });

如果是多條許可權直接在後邊新增,也可以寫成陣列新增進去。上邊的方法如果有多個許可權的時候,會多次呼叫。也可以使用下邊的方法:

new RxPermissions(TakePhotoActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        .subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //所有許可權都開啟aBoolean才為true,否則為false
                    toast("許可權已開啟");
                } else {
                    toast("許可權被拒絕,請在設定裡面開啟相應許可權,若無相應許可權會影響使用");
                }
            }
        });