總起
安卓應(yīng)用在用戶安裝的時(shí)候會(huì)跳出一大列權(quán)限要求,例如定位呀讀取通訊錄呀什么的,這有時(shí)讓使用者認(rèn)為應(yīng)用 總是亂要一些它并不需要的權(quán)限,從而引起用戶的反感甚至可能拒絕安裝。
所以與其在應(yīng)用安裝的時(shí)候羅列出一大堆權(quán)限,有時(shí)不如只列舉一些必要的權(quán)限,剩下的權(quán)限等到用戶真正使用到某個(gè)功能的時(shí)候再開啟權(quán)限。
下面是關(guān)于動(dòng)態(tài)權(quán)限請(qǐng)求的英文描述:
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)用需要某個(gè)權(quán)限來實(shí)現(xiàn)功能,但是你在manifest并沒有聲明,這時(shí)候你應(yīng)該告訴用戶需要這個(gè)權(quán)限的原因以及他們能從中獲得什么便利。
例如,一個(gè)相機(jī)應(yīng)用需要相機(jī)權(quán)限很正常,但是這個(gè)硬要需要位置權(quán)限的話,用戶可能并不能理解:
oh~這應(yīng)用我只是要用來拍照的呀為什么這個(gè)小碧池要我的位置權(quán)限它要干嘛定位我偷窺我嗎好可怕(逃ε=ε=ε=┏(゜ロ゜;)┛
所以說要一些可能會(huì)引起歧義的權(quán)限就應(yīng)該跟用戶說清楚用來干嘛。

例如這個(gè)(逃
代碼實(shí)現(xiàn):
//安卓版本檢查,因?yàn)橄旅娴腸heckSelfPermission以及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)會(huì)顯示一個(gè)請(qǐng)求權(quán)限的提示對(duì)話框,當(dāng)前應(yīng)用不能配置和修改這個(gè)對(duì)話框
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
代碼流程概述
先是用checkSelfPermission進(jìn)行權(quán)限檢查,再用shouldShowRequestPermissionRationale確認(rèn),什么叫確認(rèn)呢官方文檔沒有說(攤手
只知道會(huì)返回true or false,然后我試了一下,發(fā)現(xiàn)每次拒絕請(qǐng)求的權(quán)限之后,下次打開應(yīng)用繼續(xù)會(huì)彈出snackbar,
只有當(dāng)拒絕請(qǐng)求的權(quán)限并選中不再提醒的時(shí)候,以后再次打開應(yīng)用才不會(huì)出現(xiàn)snackbar。
暫時(shí)認(rèn)為shouldShowRequestPermissionRationale是用來檢查用戶是否同意再次請(qǐng)求權(quán)限的方法,之后我了解一下再補(bǔ)充說明。
endding
以上就是動(dòng)態(tài)權(quán)限請(qǐng)求的簡單介紹&代碼實(shí)現(xiàn)咯,咱第一篇簡書~