2019-04-21安卓权限工具

2019-04-21  本文已影响0人  奥雷里亚诺下划线_上校

工具包github网址:https://github.com/tbruyelle/RxPermissions

1.安装:最低sdk要11以上

导入依赖

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
}

2.Usage

创建一个RxPermissions实例

final RxPermissions rxPermissions = new RxPermissions(this); 
// where this is an Activity or Fragment instance

注意:
new RxPermissions(this) the this parameter can be a FragmentActivity or a Fragment. If you are using RxPermissions inside of a fragment you should pass the fragment instance(new RxPermissions(this)) as constructor parameter rather than new RxPermissions(fragment.getActivity()) or you could face a java.lang.IllegalStateException: FragmentManager is already executing transactions.

重要:

然后在AndroidManifest.xml文件中声明需要获取的权限,示例,请求读写外部存储的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
之后就可以通过创建的对象来获取权限,一般权限获取放在加载页就进行访问。

// Must be done during an initialization phase like onCreate
rxPermissions
    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });

一次申请多个权限

//获得多个权限    
    public void getMorePErmission(){
        rxPermissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                    } else {
                        // At least one permission is denied
                    }
                });
    }

用户多次拒绝后不在提示权限申请,弹toast案例(也可以弹提示或者跳转页面)

public void getMoreRequestPermission(){
        rxPermissions
                .requestEach(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Toast.makeText(getApplicationContext(),permission.name + "获得权限",Toast.LENGTH_LONG).show();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                        Toast.makeText(getApplicationContext(),permission.name +"拒绝将无法使用相机进行拍照",Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getApplicationContext(),permission.name +"请去设置-应用-自行打开文件访问权限!",Toast.LENGTH_LONG).show();
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }
上一篇 下一篇

猜你喜欢

热点阅读