Android之6.0 权限申请封装

之前一篇博客初试了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() {@Overridepublic 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方法。

 @Overridepublic 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;@Overrideprotected 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() {@Overridepublic void run() {getContacts();}}, new Runnable() {@Overridepublic void run() {getContactsDenied();}});}





本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/293515.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Samba服务器问题汇总

一个Samba服务器要么经典模式访问&#xff08;用户名密码&#xff09;&#xff0c;要么友好访问&#xff08;guest&#xff09;&#xff0c;只可选其一。㈠准备工作&#xff1a;1>清除客户端windows系统的上次访问自动记录CMD下运行&#xff1a;net use * /delete /y2>关…

Unity手游之路lt;七gt;角色控制器

我们要控制角色的移动&#xff0c;能够所有细节都由自己来实现。控制角色模型的移动&#xff0c;同一时候移动摄影机&#xff0c;改变视角。当然Unity也提供了一些组件&#xff0c;能够让我们做更少的工作&#xff0c;实现我们所期望的功能。今天我们就一起系统来学习相关的内容…

《SAS编程与数据挖掘商业案例》学习笔记之十八

接着以前的《SAS编程与数据挖掘商业案例》&#xff0c;之前全是sas的基础知识&#xff0c;现在开始进入数据挖掘方面笔记&#xff0c;本文主要介绍数据挖掘基本流程以及应用方向&#xff0c;并以logistic回归为例说明。 一&#xff1a;数据挖掘综述 衡量一个数据挖掘模型价值的…

开源软件的痛点

| 作者&#xff1a;Bob Jiang| 编辑&#xff1a;刘雪洁| 责编&#xff1a;王玥敏| 设计&#xff1a;宋传琪开篇我是 Bob Jiang (个人博客&#xff1a;https://www.bobjiang.com/)&#xff0c;开源软件领域的新人。我从2018年加入区块链领域开始认识和了解开源。当时我创立了HiB…

【CodeForces 577C】Vasya and Petya’s Game

链接 某个数x属于[1,n]&#xff0c;至少询问哪些数y“x是否是y的倍数”才能判断x。找出所有质因数和质因数的幂即可。 #include<cstdio> #include<algorithm> #define N 1005 using namespace std; int n,pr[N],ans[N],cnt; int main(){scanf("%d",&…

Andorid之华为手机开发模式不打印日志

用华为手机测试程序是&#xff0c;eclipse的logcat不能打印日志&#xff0c;我按照网上说的方法打开了windows下面的show view 的logcat&#xff0c;日志有logcat但是日志不打印&#xff0c;调试程序必须要日志&#xff0c;最后终于搜到了这个调试方法&#xff0c;在手机拨号界…

SQLite入门之数据类型

2019独角兽企业重金招聘Python工程师标准>>> SQLite入门之数据类型 2011-05-23 16:47:47 来源&#xff1a;SeaYee 最近在开发一个可以记录日志的程序&#xff0c;要求效率高&#xff0c;需要能做简单的查询和统计。经过同事介绍&#xff0c;看上了SQLite。首先了解…

【Tika基础教程之一】Tika基础教程

一、快速入门 1、Tika是一个用于文本解释的框架&#xff0c;其本身并不提供任何的库用于解释文本&#xff0c;而是调用各种各样的库&#xff0c;如POI&#xff0c;PDFBox等。 使用Tika&#xff0c;可以提取文件中的作者、标题、创建时间、正文等内容&#xff0c;相比于java.io自…

它是世界上最轻的固体!1000℃下不会熔化,上过火星,还能进你家......

全世界只有3.14 % 的人关注了爆炸吧知识小果冻大难关开学了&#xff0c;8岁表妹逮着这个机会讹了我一大箱果冻&#xff0c;超模君糊里糊涂就进了这只神兽的套。今天估计是一口气吃了太多&#xff0c;腻了&#xff0c;一边用手敲着果冻一边问超模君&#xff1a;“这果冻这么软&a…

使用C#快速生成二维码 | 真正跨平台方案

前言二维码&#xff08;QR Code&#xff09;&#xff0c;与传统的一维码&#xff0c;比如条形码&#xff0c;二维码具有存储的数据量更大&#xff1b;可以包含数字、字符&#xff0c;及中文文本等混合内容&#xff1b;有一定的容错性&#xff08;在部分损坏以后还可以正常读取&…

Andorid之MediaPlayer和AudioTrack播放Audio的区别与联系

播放声音可以用MediaPlayer和AudioTrack&#xff0c;两者都提供了java API供应用开发者使用。虽然都可以播放声音&#xff0c;但两者还是有很大的区别的。 其中最大的区别是MediaPlayer可以播放多种格式的声音文件&#xff0c;例如MP3&#xff0c;AAC&#xff0c;WAV&#xff0…

《SAS编程与数据挖掘商业案例》学习笔记之十七

继续读书笔记&#xff0c;本次重点sas sql语句&#xff0c;由于sql内容多且复杂&#xff0c;本文只介绍商业应用中常用的并且容易出错的地方&#xff0c;内容包括&#xff1a;单表操作、多表关联、子查询以及merge和join的区别 1.单表操作 eg1&#xff1a; Proc sql outobs10&a…

制作一个类似苹果VFL的格式化语言来描述UIStackView

在项目中总是希望页面上各处的文字&#xff0c;颜色&#xff0c;字体大小甚至各个视图控件布局都能够在发版之后能够修改以弥补一些前期考虑不周&#xff0c;或者根据统计数据能够随时进行调整&#xff0c;当然是各个版本都能够统一变化。看到这样的要求后&#xff0c;第一反应…

[Android] TextView 分页功能的实现

为什么80%的码农都做不了架构师&#xff1f;>>> 分页功能是阅读器类软件的基本功能之一, 也是自己之前写阅读器时遇到的第一个问题. 尝试了不少办法才解决, 现在把其中最容易实现的一个方法记录下来, 也方便大家参考. 基本思路如下: 从文件中读取 8000 个字符至缓冲…

把男朋友变成儿子你只需要一秒

1 别人以为的我▼2 幸好有监控&#xff0c;差点就没法和老婆解释了&#xff01;▼3 为了卖化妆品我已经不止一次假装我有一群舔狗了▼4 这么多年下来班主任的这些套路谁还不清楚呢&#xff1f;▼5 司机同志们注意啦要主动停车接受检查▼6 让男友变儿子你只需要一秒钟▼7 …

thinkphp与php共享session

在其他php页面添加如下代码即可 if (!session_id()) session_start(); 使用时 thinphp 使用 session(test,123); $user_info $_SESSION[test]; var_dump($test); //123 转载于:https://www.cnblogs.com/yun007/p/3806385.html

Android之使用HandlerThread 以及如何退出总结

1 、使用 HandlerThread handlerThread = new HandlerThread("handlerThread"); handlerThread.start(); //这里获取到HandlerThread的runloop MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 2、介绍 和主线程已经没有关系了,所以不能跟新…

容器界的新“朋友”

微软中国MSDN 点击上方蓝字关注我们Ignite 2021 上&#xff0c;微软发布了Azure Container Apps&#xff0c;这是一种以无服务器应用程序为中心的托管服务&#xff0c;用户看不到或无需管理任何底层 VM、协调器或其他云基础架构。Azure Container Apps支持打包在容器中的任何应…

分析函数在数据分析中的应用

我们来看看下面的几个典型例子&#xff1a; ①查找上一年度各个销售区域排名前10的员工 ②按区域查找上一年度订单总额占区域订单总额20%以上的客户 ③查找上一年度销售最差的部门所在的区域 ④查找上一年度销售最好和最差的产品 我们看看上面的几个例子就可以感觉到这几个查询…