Android之6.0 权限申请封装

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

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


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

1. ContextCompat.checkSelfPermission() 

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


       /**
       * Determine whether <em>you</em> have been granted a particular permission.
       *
       * @param permission The name of the permission being checked.
       *
       * @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if you have the
       * permission, or {@link android.content.pm.PackageManager#PERMISSION_DENIED} if not.
       *
       * @see android.content.pm.PackageManager#checkPermission(String, String)
       */
       public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {
       if (permission == null) {
       throw new IllegalArgumentException("permission is null");
       }
       return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());
       }
  
 

2、ActivityCompat.requestPermissions()


      /**
       * Requests permissions to be granted to this application. These permissions
       * must be requested in your manifest, they should not be granted to your app,
       * and they should have protection level {@link android.content.pm.PermissionInfo
       * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
       * the platform or a third-party app.
       * <p>
       * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
       * are granted at install time if requested in the manifest. Signature permissions
       * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
       * install time if requested in the manifest and the signature of your app matches
       * the signature of the app declaring the permissions.
       * </p>
       * <p>
       * If your app does not have the requested permissions the user will be presented
       * with UI for accepting them. After the user has accepted or rejected the
       * requested permissions you will receive a callback reporting whether the
       * permissions were granted or not. Your activity has to implement {@link
       * android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback}
       * and the results of permission requests will be delivered to its {@link
       * android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(
       * int, String[], int[])} method.
       * </p>
       * <p>
       * Note that requesting a permission does not guarantee it will be granted and
       * your app should be able to run without having this permission.
       * </p>
       * <p>
       * This method may start an activity allowing the user to choose which permissions
       * to grant and which to reject. Hence, you should be prepared that your activity
       * may be paused and resumed. Further, granting some permissions may require
       * a restart of you application. In such a case, the system will recreate the
       * activity stack before delivering the result to your onRequestPermissionsResult(
       * int, String[], int[]).
       * </p>
       * <p>
       * When checking whether you have a permission you should use {@link
       * #checkSelfPermission(android.content.Context, String)}.
       * </p>
       *
       * @param activity The target activity.
       * @param permissions The requested permissions.
       * @param requestCode Application specific request code to match with a result
       * reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
       * int, String[], int[])}.
       *
       * @see #checkSelfPermission(android.content.Context, String)
       * @see #shouldShowRequestPermissionRationale(android.app.Activity, String)
       */
       public static void requestPermissions(final @NonNull Activity activity,
       final @NonNull String[] permissions, final int requestCode) {
       if (Build.VERSION.SDK_INT >= 23) {
       ActivityCompatApi23.requestPermissions(activity, permissions, requestCode);
       } else if (activity instanceof OnRequestPermissionsResultCallback) {
       Handler handler = new Handler(Looper.getMainLooper());
       handler.post(new Runnable() {
       @Override
       public void run() {
       final int[] grantResults = new int[permissions.length];
       PackageManager packageManager = activity.getPackageManager();
       String packageName = activity.getPackageName();
       final int permissionCount = permissions.length;
       for (int i = 0; i < permissionCount; i++) {
       grantResults[i] = packageManager.checkPermission(
       permissions[i], packageName);
       }
       ((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(
       requestCode, permissions, grantResults);
       }
       });
       }
       }
  
 

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


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

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


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


      * @param requestId 请求授权的Id,唯一即可
       * @param permission 请求的授权
       * @param allowableRunnable 同意授权后的操作
       * @param disallowableRunnable 禁止授权后的操作
       **/
       protected void requestPermission(int requestId, String permission,
       Runnable allowableRunnable, Runnable disallowableRunnable) {
       if (allowableRunnable == null) {
       throw new IllegalArgumentException("allowableRunnable == null");
       }
       allowablePermissionRunnables.put(requestId, allowableRunnable);
       if (disallowableRunnable != null) {
       disallowblePermissionRunnables.put(requestId, disallowableRunnable);
       }
       //版本判断
       if (Build.VERSION.SDK_INT >= 23) {
       //检查是否拥有权限
       int checkPermission = ContextCompat.checkSelfPermission(MyApplication.getContext(), permission);
       if (checkPermission != PackageManager.PERMISSION_GRANTED) {
       //弹出对话框请求授权
       ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestId);
       return;
       } else {
       allowableRunnable.run();
       }
       } else {
       allowableRunnable.run();
       }
       }
  
 
4、实现onRequestPermissionsResult方法。


       @Override
       public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
       Runnable allowRun=allowablePermissionRunnables.get(requestCode);
       allowRun.run();
       }else {
       Runnable disallowRun = disallowblePermissionRunnables.get(requestCode);
       disallowRun.run();
       }
       }
  
 
5、调用


      public static final String CONTACT_PERMISSION = android.Manifest.permission.READ_CONTACTS;
       public static final int readContactRequest = 1;
        @Override
       protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.content_get_contacts);
       ContactsLv = (ListView) findViewById(R.id.ContactsLv);
       adapter = new ContactsAdapter(list, this);
       ContactsLv.setAdapter(adapter);
       requestPermission(readContactRequest, CONTACT_PERMISSION, new Runnable() {
       @Override
       public void run() {
       getContacts();
       }
       }, new Runnable() {
       @Override
       public void run() {
       getContactsDenied();
       }
       });
       }
  
 





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

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

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

作者其他文章

评论(0

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

    全部回复

    上滑加载中

    设置昵称

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

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

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