適配 Android 6.0 (API level 23)
官方文檔的步驟
(我建議你去看文檔限煞,不要看我的文章抹恳,我是給自己看的)
官方路徑:
https://developer.android.com/training/permissions/requesting.html
1、檢查權(quán)限
int permissionCheck =ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS);
這里的permissionCheck只有兩個返回值:
(1)PackageManager.PERMISSION_GRANTED署驻,app已經(jīng)有了這個權(quán)限奋献,你想干嘛就繼續(xù)干下去吧,下面的文章也不用看旺上;
(2) PERMISSION_DENIED瓶蚂,app還沒有權(quán)限呢,這時候你就慘了宣吱,一系列的問題要處理窃这,往下看吧;
2征候、注冊權(quán)限
由于上一步檢查到APP還沒有權(quán)限讀聯(lián)系人,所以我就要引導(dǎo)用戶允許這個權(quán)限杭攻。
(1)提醒用戶
提醒用戶,要讀取用戶的聯(lián)系人信息來做壞事了疤坝,噢兆解,不是啦,幫用戶找到用這個APP的好友啦跑揉。
activity的話可以調(diào)用:
boolean shouldShow=ActivityCompat.shouldShowRequestPermissionRationale(myActivity, perm);
fragment的話可以調(diào)用:
boolean shouldShow=myFragment.shouldShowRequestPermissionRationale(perm);
拿shouldShow的值來說:
返回true锅睛,就是APP在之前已經(jīng)向用戶申請過這個權(quán)限了,但是被用戶狠心的拒絕了历谍。
返回false现拒,更加嚴(yán)重,APP之前向用戶申請讀取聯(lián)系人的時候望侈,用戶不單單拒絕了還選擇了“不要再提醒了”具练,或者是你在系統(tǒng)的設(shè)置里對APP關(guān)閉了權(quán)限。
所以這句也是在獲取不到權(quán)限的情況下甜无,應(yīng)該作為第一條語句執(zhí)行扛点。跟用戶解釋下為啥要用這個權(quán)限呢,因?yàn)橹翱赡苡脩舨焕斫狻?/p>
(2)正式注冊
requestPermissions();
上面那一步提示無論執(zhí)行岂丘,或者沒有執(zhí)行陵究,接下來都需要調(diào)用requestPermissions()彈個框給用戶選擇,這個才是真正目的奥帘。上面就是一個提示而已铜邮,給用戶看看,沒啥鳥用。
3松蒜、整個流程
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
4扔茅、那我怎么知道用戶對框的操作
調(diào)用activity或者fragment的onRequestPermissionsResult()方法:
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}