android动态权限请求简单教程

总起

安卓应用在用户安装的时候会跳出一大列权限要求,例如定位呀读取通讯录呀什么的,这有时让使用者认为应用 总是乱要一些它并不需要的权限,从而引起用户的反感甚至可能拒绝安装。

所以与其在应用安装的时候罗列出一大堆权限,有时不如只列举一些必要的权限,剩下的权限等到用户真正使用到某个功能的时候再开启权限。

下面是关于动态权限请求的英文描述:

boolean shouldShowRequestPermissionRationale (Activity activity, String permission)
 Gets whether you should show UI with rationale for requesting a permission. 
 You should do this only if you do not have the permission and the context in which the permission
 is requested does not clearly communicate to the user what would be the benefit from granting this permission.

For example, if you write a camera app, requesting the camera permission would be expected by the user 
and no rationale for why it is requested is needed. If however, the app needs location for tagging photos 
then a non-tech savvy user may wonder how location is related to taking photos. In this case you may 
choose to show UI with rationale of requesting this permission.

用我的话翻译过来就是:

你的应用需要某个权限来实现功能,但是你在manifest并没有声明,这时候你应该告诉用户需要这个权限的原因以及他们能从中获得什么便利。
例如,一个相机应用需要相机权限很正常,但是这个硬要需要位置权限的话,用户可能并不能理解:
    oh~这应用我只是要用来拍照的呀为什么这个小碧池要我的位置权限它要干嘛定位我偷窥我吗好可怕(逃ε=ε=ε=┏(゜ロ゜;)┛

所以说要一些可能会引起歧义的权限就应该跟用户说清楚用来干嘛。
android动态权限请求简单教程_第1张图片
Screenshot_20161016-002058.png

例如这个(逃

代码实现:

//安卓版本检查,因为下面的checkSelfPermission以及shouldShowRequestPermissionRationale都是API23才开始支持的
//API23是android6.0,即android M
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {return true;}
//权限检查
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
    Log.i(TAG,"permission has opened");return true;}
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
    Log.i(TAG,"opening permission");
    Snackbar.make(actv_email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onClick(View v) {
            //用snackbar来向用户解释:为什么我们需要某权限
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
    }).show();
} else {
    //系统会显示一个请求权限的提示对话框,当前应用不能配置和修改这个对话框
    requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}

代码流程概述

先是用checkSelfPermission进行权限检查,再用shouldShowRequestPermissionRationale确认,什么叫确认呢官方文档没有说(摊手

只知道会返回true or false,然后我试了一下,发现每次拒绝请求的权限之后,下次打开应用继续会弹出snackbar,

只有当拒绝请求的权限并选中不再提醒的时候,以后再次打开应用才不会出现snackbar。

暂时认为shouldShowRequestPermissionRationale是用来检查用户是否同意再次请求权限的方法,之后我了解一下再补充说明。

endding

以上就是动态权限请求的简单介绍&代码实现咯,咱第一篇~

你可能感兴趣的:(android动态权限请求简单教程)