總起
安卓應(yīng)用在用戶安裝的時候會跳出一大列權(quán)限要求,例如定位呀讀取通訊錄呀什么的面粮,這有時讓使用者認(rèn)為應(yīng)用 總是亂要一些它并不需要的權(quán)限少孝,從而引起用戶的反感甚至可能拒絕安裝。
所以與其在應(yīng)用安裝的時候羅列出一大堆權(quán)限熬苍,有時不如只列舉一些必要的權(quán)限稍走,剩下的權(quán)限等到用戶真正使用到某個功能的時候再開啟權(quán)限。
下面是關(guān)于動態(tài)權(quán)限請求的英文描述:
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.
用我的話翻譯過來就是:
你的應(yīng)用需要某個權(quán)限來實現(xiàn)功能柴底,但是你在manifest并沒有聲明婿脸,這時候你應(yīng)該告訴用戶需要這個權(quán)限的原因以及他們能從中獲得什么便利。
例如柄驻,一個相機應(yīng)用需要相機權(quán)限很正常狐树,但是這個硬要需要位置權(quán)限的話,用戶可能并不能理解:
oh~這應(yīng)用我只是要用來拍照的呀為什么這個小碧池要我的位置權(quán)限它要干嘛定位我偷窺我嗎好可怕(逃ε=ε=ε=┏(゜ロ゜;)┛
所以說要一些可能會引起歧義的權(quán)限就應(yīng)該跟用戶說清楚用來干嘛鸿脓。
Screenshot_20161016-002058.png
例如這個(逃
代碼實現(xiàn):
//安卓版本檢查抑钟,因為下面的checkSelfPermission以及shouldShowRequestPermissionRationale都是API23才開始支持的
//API23是android6.0,即android M
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {return true;}
//權(quán)限檢查
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來向用戶解釋:為什么我們需要某權(quán)限
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}).show();
} else {
//系統(tǒng)會顯示一個請求權(quán)限的提示對話框野哭,當(dāng)前應(yīng)用不能配置和修改這個對話框
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
代碼流程概述
先是用checkSelfPermission進行權(quán)限檢查在塔,再用shouldShowRequestPermissionRationale確認(rèn),什么叫確認(rèn)呢官方文檔沒有說(攤手
只知道會返回true or false拨黔,然后我試了一下蛔溃,發(fā)現(xiàn)每次拒絕請求的權(quán)限之后,下次打開應(yīng)用繼續(xù)會彈出snackbar篱蝇,
只有當(dāng)拒絕請求的權(quán)限并選中不再提醒的時候贺待,以后再次打開應(yīng)用才不會出現(xiàn)snackbar。
暫時認(rèn)為shouldShowRequestPermissionRationale是用來檢查用戶是否同意再次請求權(quán)限的方法态兴,之后我了解一下再補充說明狠持。
endding
以上就是動態(tài)權(quán)限請求的簡單介紹&代碼實現(xiàn)咯,咱第一篇簡書~