【Android】使用PermissionsDispatcher动态权限库进行权限适配

PermissionsDispatcher

PermissionsDispatcher是基于注解来写的库,即在需要的方法上添加对应的注解,然后它会在适当的时候调用被注解过的对应的方法。

PermissionsDispatcher官方对其解释:
PermissionsDispatcher provides a simple annotation-based API to handle runtime permissions.
// PermissionsDispatcher提供了一个简单的基于注解的API来处理运行时权限。
This library lifts the burden that comes with writing a bunch of check statements whether a permission has been granted or not from you, in order to keep your code clean and safe.
这个库可以通过编写一堆检查语句来解除这个负担,这些检查语句是为了让代码保持干净和安全,是否授予您的权限。


1.在项目中引入PermissionsDispatcher

在app module的build.gradle文件中添加一下内容(${latest.version}更换为最新的版本号):

dependencies {
  compile("com.github.hotchemi:permissionsdispatcher:${latest.version}") {
      // if you don't use android.app.Fragment you can exclude support for them
      // 如果你不使用andorid.app.Fragment,可以排除对它们的支持。
      exclude module: "support-v13"
  }
  annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:${latest.version}"
}

在project的build.gradle中添加如下内容:

repositories {
  jcenter()
  maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}

2.在AndroidManifest.xml文件中配置应用所需要的权限



3.添加注解(这里以在Activity中的使用为例)

PermissionsDispatcher introduces only a few annotations, keeping its general API concise:
// PermissionsDispatcher引入了一些注解,使其API简洁

NOTE: Annotated methods must not be private.
// 注意:注解方法不能使私有的。

PermissionsDispatcher目前支持下面5个注解:

Annotation(注解) Required(是否必须使用) Description(描述/说明)
@RuntimePermissions Register an Activity or Fragment(we support both) to handle permissions.
@NeedsPermission Annotate a method which performs the action that requires one or more permissions.
@OnShowRationale Annotate a method which explains why the permission/s is/are needed. It passes in a PermissionRequest object which can be used to continue or abort the current permission request upon user input.
@OnPermissionDenied Annotate a method which is invoked if the user doesn't grant the permissions.
@OnNeverAskAgain Annotate a method which is invoked if the user chose to have the device "never ask again" about a permission.
  • 添加@RuntimePermissions注解:
    这是必须使用的注解,在想要进行权限申请的Activity或者Fragment上使用:
// 1.Register an Activity or Fragment(we support both) to handle permissions.
//   注册一个Activity或Fragment(我们支持两者)来处理权限。[必须的注解]
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

}
  • 添加@NeedsPermission注解:
    必须使用的注解,标注在你要获取权限的方法上,括号内传入需要申请的一个或多个权限,在获取到权限后会回调该方法。
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    // 2.Annotate a method which performs the action that requires one or more permissions.
    //   注解一个执行需要获取一个或多个权限的操作的方法。[必须的注解]
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        Toast.makeText(this, "已获取到相机权限", Toast.LENGTH_SHORT).show();
    }

}
  • 添加@OnShowRationale注解:
    非必要注解,注解在用户首次拒绝后,再次获取权限时解释为什么需要获取权限的方法上。
    // 3.Annotate a method which explains why the permission/s is/are needed. It passes in a
    // PermissionRequest object which can be used to continue or abort the current
    // permission request upon user input.
    // 注解一种解释为什么需要权限的方法(注解用户首次拒绝后,再次获取权限时给出提示的方法)。它通过PermissionRequest对象,
    // 该对象可用于在用户输入时继续或中止当前权限请求。[非必须的注释]
    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(R.string.permission_camera_rationale)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }
  • 添加@OnPermissionDenied注解:
    非必要注解,注解一个用户拒绝授权时回调的方法。
    // 4.Annotate a method which is invoked if the user doesn't grant the permissions
    //  注解一个用户拒绝授权时回调的方法。[非必须的注释]
    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "相机权限许可被拒绝,请考虑给予权限以便进行拍照操作。", Toast.LENGTH_SHORT).show();
    }
  • 添加@OnNeverAskAgain注解:
    非必要注解,注解一个用户选择"不再询问"时进行提示的回调方法。

注:也可在这里跳转进入到权限设置页。

    // 5.Annotate a method which is invoked if the user chose to have the device "never ask again"
    // about a permission
    // 注解一个用户选择"不再询问"时进行提示的回调方法。[非必须的注释]
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "相机许可被拒绝,不再进行询问。", Toast.LENGTH_SHORT).show();
    }

4.将权限管理委托给生成的方法(使用&状态回调)

  • 主动请求获取权限
    在编译过程中,PermissionsDispatcher会根据([Activity Name] + PermissionsDispatcher)的命名规则生成一个类,您可以使用它安全地访问这些受保护的方法。

注:如MainActivity生成后的类名为MainActivityPermissionsDispatcher

那么,我们可以通过以下方法去获取相机权限:

    // NOTE: delegate the permission handling to generated method.
    // 注意:将权限处理委托给生成的方法。
    MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
  • 在onRequestPermissionsResult中添加回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        // 注意:将权限处理委托给生成的方法。
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

MainActivty.java代码

// 1.Register an Activity or Fragment(we support both) to handle permissions.
//   注册一个Activity或Fragment(我们支持两者)来处理权限。[必须的注解]
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.main_btn_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // NOTE: delegate the permission handling to generated method.
                // 注意:将权限处理委托给生成的方法。
                MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
            }
        });
    }

    // 2.Annotate a method which performs the action that requires one or more permissions.
    //   注解一个执行需要获取一个或多个权限的操作的方法。[必须的注解]
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        Toast.makeText(this, "已获取到相机权限", Toast.LENGTH_SHORT).show();
    }

    // 3.Annotate a method which explains why the permission/s is/are needed. It passes in a
    // PermissionRequest object which can be used to continue or abort the current
    // permission request upon user input.
    // 注解一种解释为什么需要权限的方法(注解获取权限时给出提示的方法)。它通过PermissionRequest对象,
    // 该对象可用于在用户输入时继续或中止当前权限请求。[非必须的注释]
    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(R.string.permission_camera_rationale)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝" new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 4.Annotate a method which is invoked if the user doesn't grant the permissions
    //  注解一个用户拒绝授权时回调的方法。[非必须的注释]
    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "相机权限许可被拒绝,请考虑给予权限以便进行拍照操作。", Toast.LENGTH_SHORT).show();
    }

    // 5.Annotate a method which is invoked if the user chose to have the device "never ask again"
    // about a permission
    // 注解一个用户选择"不再询问"时进行提示的回调方法。[非必须的注释]
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "相机许可被拒绝,不再进行询问。", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        // 注意:将权限处理委托给生成的方法。
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}

你可能感兴趣的:(【Android】使用PermissionsDispatcher动态权限库进行权限适配)