1.配置
在app层的build.gradle中
dependencies {
// Permissions Dispatcher compile 'com.github.hotchemi:permissionsdispatcher:2.3.1' annotationProcessor 'com.github.hotchemi:permissionsdispatcher-processor:2.3.1'
}
这种配置需要有个条件:Android Gradle Plugin >= 2.2
2.举例
这个库用到了5个注解:
注解是否必须描述
@RuntimePermissions是注册在Acttivity或者Fragment上
@NeedsPermission是再需要权限的方法上注册
@OnShowRationale否被注解的方法可以提示为什么需要这个权限
@OnPermissionDenied否如果用户拒绝了权限申请那么调用该方法
@OnNeverAskAgain否如果用户选择了不再询问,调用该方法
这个库用到了Annotion Processor,需要用到一个应用编译期间产生的类,这个类的命名是:类名+PermissionsDispatcher。
@RuntimePermissionspublicclassThirdActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); findViewById(R.id.button).setOnClickListener(newView.OnClickListener() {@OverridepublicvoidonClick(View v) { ThirdActivityPermissionsDispatcher.showContactsWithCheck(ThirdActivity.this); } }); }@OverridepublicvoidonRequestPermissionsResult(intrequestCode, @NonNull String[] permissions, @NonNullint[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults); ThirdActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults); }@NeedsPermission({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})publicvoidshowContacts() { Toast.makeText(this,"读取通讯录", Toast.LENGTH_SHORT).show(); }@OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})publicvoidonContactsDenied() { Toast.makeText(this,"onContactsDenied", Toast.LENGTH_SHORT).show(); }@OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})publicvoidonContactsNeverAskAgain() { Toast.makeText(this,"onContactsNeverAskAgain", Toast.LENGTH_SHORT).show();newAppSettingsDialog.Builder(this) .setTitle("请求权限") .setRationale("需要开启启用相机的权限才能继续下去!") .build() .show(); }@OnShowRationale({Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS})publicvoidshowRationaleContacts(finalPermissionRequest request) {// Toast.makeText(this, "showRationaleContacts", Toast.LENGTH_SHORT).show();newAlertDialog.Builder(this) .setPositiveButton("继续",newDialogInterface.OnClickListener() {@OverridepublicvoidonClick(@NonNull DialogInterface dialog,intwhich) { request.proceed(); } }) .setNegativeButton("取消",newDialogInterface.OnClickListener() {@OverridepublicvoidonClick(@NonNull DialogInterface dialog,intwhich) { request.cancel(); } }) .setCancelable(false) .setMessage("需要通讯录权限") .show(); }}
Demo: https://download.csdn.net/download/android2me/9810618