Android之6.0 权限申请封装

举报
chenyu 发表于 2021/07/27 01:26:32 2021/07/27
【摘要】 之前一篇博客初试了Android6.0系统的动态权限申请,成功之后开始思考将权限申请功能封装以供更加方便的调用。 查阅6.0系统权限相关的API,整个权限申请需要调用三个方法: 1. ContextCompat.checkSelfPermission()  检查应用是否拥有该权限,被授权返回值为PERMISSION_GRANTED,否则返回PERM...

之前一篇博客初试了Android6.0系统的动态权限申请,成功之后开始思考将权限申请功能封装以供更加方便的调用。


查阅6.0系统权限相关的API,整个权限申请需要调用三个方法:

1. ContextCompat.checkSelfPermission() 

检查应用是否拥有该权限,被授权返回值为PERMISSION_GRANTED,否则返回PERMISSION_DENIED


  
  1. /**
  2. * Determine whether <em>you</em> have been granted a particular permission.
  3. *
  4. * @param permission The name of the permission being checked.
  5. *
  6. * @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if you have the
  7. * permission, or {@link android.content.pm.PackageManager#PERMISSION_DENIED} if not.
  8. *
  9. * @see android.content.pm.PackageManager#checkPermission(String, String)
  10. */
  11. public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
  12. if (permission == null) {
  13. throw new IllegalArgumentException("permission is null");
  14. }
  15. return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
  16. }

2、ActivityCompat.requestPermissions()


  
  1. /**
  2. * Requests permissions to be granted to this application. These permissions
  3. * must be requested in your manifest, they should not be granted to your app,
  4. * and they should have protection level {@link android.content.pm.PermissionInfo
  5. * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
  6. * the platform or a third-party app.
  7. * <p>
  8. * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
  9. * are granted at install time if requested in the manifest. Signature permissions
  10. * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
  11. * install time if requested in the manifest and the signature of your app matches
  12. * the signature of the app declaring the permissions.
  13. * </p>
  14. * <p>
  15. * If your app does not have the requested permissions the user will be presented
  16. * with UI for accepting them. After the user has accepted or rejected the
  17. * requested permissions you will receive a callback reporting whether the
  18. * permissions were granted or not. Your activity has to implement {@link
  19. * android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback}
  20. * and the results of permission requests will be delivered to its {@link
  21. * android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(
  22. * int, String[], int[])} method.
  23. * </p>
  24. * <p>
  25. * Note that requesting a permission does not guarantee it will be granted and
  26. * your app should be able to run without having this permission.
  27. * </p>
  28. * <p>
  29. * This method may start an activity allowing the user to choose which permissions
  30. * to grant and which to reject. Hence, you should be prepared that your activity
  31. * may be paused and resumed. Further, granting some permissions may require
  32. * a restart of you application. In such a case, the system will recreate the
  33. * activity stack before delivering the result to your onRequestPermissionsResult(
  34. * int, String[], int[]).
  35. * </p>
  36. * <p>
  37. * When checking whether you have a permission you should use {@link
  38. * #checkSelfPermission(android.content.Context, String)}.
  39. * </p>
  40. *
  41. * @param activity The target activity.
  42. * @param permissions The requested permissions.
  43. * @param requestCode Application specific request code to match with a result
  44. * reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
  45. * int, String[], int[])}.
  46. *
  47. * @see #checkSelfPermission(android.content.Context, String)
  48. * @see #shouldShowRequestPermissionRationale(android.app.Activity, String)
  49. */
  50. public static void requestPermissions(final @NonNull Activity activity,
  51. final @NonNull String[] permissions, final int requestCode) {
  52. if (Build.VERSION.SDK_INT >= 23) {
  53. ActivityCompatApi23.requestPermissions(activity, permissions, requestCode);
  54. } else if (activity instanceof OnRequestPermissionsResultCallback) {
  55. Handler handler = new Handler(Looper.getMainLooper());
  56. handler.post(new Runnable() {
  57. @Override
  58. public void run() {
  59. final int[] grantResults = new int[permissions.length];
  60. PackageManager packageManager = activity.getPackageManager();
  61. String packageName = activity.getPackageName();
  62. final int permissionCount = permissions.length;
  63. for (int i = 0; i < permissionCount; i++) {
  64. grantResults[i] = packageManager.checkPermission(
  65. permissions[i], packageName);
  66. }
  67. ((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(
  68. requestCode, permissions, grantResults);
  69. }
  70. });
  71. }
  72. }

3、AppCompatActivity.onRequestPermissionsResult() 
该方法类似于Activity的OnActivityResult()的回调方法,主要接收请求授权的返回值


下面开始在项目中进行权限封装: 
1、新建一个BaseActivity活动,extends自AppCompatActivity。这里将权限申请设计成基类,让项目中的所有活动都继承BaseActivity类。 
延伸学习:关于extends和implements的区别参考

2、声明两个Map类型的变量,用于存放取得权限后的运行和未获取权限时的运行。 
延伸学习:java中Map,List与Set的区别


  
  1. private Map<Integer, Runnable> allowablePermissionRunnables = new HashMap<>();
  2. private Map<Integer, Runnable> disallowblePermissionRunnables = new HashMap<>();
3、实现requesPermission方法。


  
  1. * @param requestId 请求授权的Id,唯一即可
  2. * @param permission 请求的授权
  3. * @param allowableRunnable 同意授权后的操作
  4. * @param disallowableRunnable 禁止授权后的操作
  5. **/
  6. protected void requestPermission(int requestId, String permission,
  7. Runnable allowableRunnable, Runnable disallowableRunnable) {
  8. if (allowableRunnable == null) {
  9. throw new IllegalArgumentException("allowableRunnable == null");
  10. }
  11. allowablePermissionRunnables.put(requestId, allowableRunnable);
  12. if (disallowableRunnable != null) {
  13. disallowblePermissionRunnables.put(requestId, disallowableRunnable);
  14. }
  15. //版本判断
  16. if (Build.VERSION.SDK_INT >= 23) {
  17. //检查是否拥有权限
  18. int checkPermission = ContextCompat.checkSelfPermission(MyApplication.getContext(), permission);
  19. if (checkPermission != PackageManager.PERMISSION_GRANTED) {
  20. //弹出对话框请求授权
  21. ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestId);
  22. return;
  23. } else {
  24. allowableRunnable.run();
  25. }
  26. } else {
  27. allowableRunnable.run();
  28. }
  29. }
4、实现onRequestPermissionsResult方法。


  
  1. @Override
  2. public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  3. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  4. if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
  5. Runnable allowRun=allowablePermissionRunnables.get(requestCode);
  6. allowRun.run();
  7. }else {
  8. Runnable disallowRun = disallowblePermissionRunnables.get(requestCode);
  9. disallowRun.run();
  10. }
  11. }
5、调用


  
  1. public static final String CONTACT_PERMISSION = android.Manifest.permission.READ_CONTACTS;
  2. public static final int readContactRequest = 1;
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.content_get_contacts);
  7. ContactsLv = (ListView) findViewById(R.id.ContactsLv);
  8. adapter = new ContactsAdapter(list, this);
  9. ContactsLv.setAdapter(adapter);
  10. requestPermission(readContactRequest, CONTACT_PERMISSION, new Runnable() {
  11. @Override
  12. public void run() {
  13. getContacts();
  14. }
  15. }, new Runnable() {
  16. @Override
  17. public void run() {
  18. getContactsDenied();
  19. }
  20. });
  21. }





文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/52040926

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200