適配 Android 6.0 (API level 23)
官方文檔的步驟
(我建議你去看文檔,不要看我的文章,我是給自己看的)
官方路徑:
https://developer.android.com/training/permissions/requesting.html

1、檢查權限
int permissionCheck =ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS);
這里的permissionCheck只有兩個返回值:
(1)PackageManager.PERMISSION_GRANTED,app已經有了這個權限,你想干嘛就繼續(xù)干下去吧,下面的文章也不用看;
(2) PERMISSION_DENIED,app還沒有權限呢,這時候你就慘了,一系列的問題要處理,往下看吧;
2、注冊權限
由于上一步檢查到APP還沒有權限讀聯(lián)系人,所以我就要引導用戶允許這個權限。
(1)提醒用戶
提醒用戶,要讀取用戶的聯(lián)系人信息來做壞事了,噢,不是啦,幫用戶找到用這個APP的好友啦。

activity的話可以調用:
boolean shouldShow=ActivityCompat.shouldShowRequestPermissionRationale(myActivity, perm);
fragment的話可以調用:
boolean shouldShow=myFragment.shouldShowRequestPermissionRationale(perm);
拿shouldShow的值來說:
返回true,就是APP在之前已經向用戶申請過這個權限了,但是被用戶狠心的拒絕了。
返回false,更加嚴重,APP之前向用戶申請讀取聯(lián)系人的時候,用戶不單單拒絕了還選擇了“不要再提醒了”,或者是你在系統(tǒng)的設置里對APP關閉了權限。
所以這句也是在獲取不到權限的情況下,應該作為第一條語句執(zhí)行。跟用戶解釋下為啥要用這個權限呢,因為之前可能用戶不理解。
(2)正式注冊
requestPermissions();
上面那一步提示無論執(zhí)行,或者沒有執(zhí)行,接下來都需要調用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、那我怎么知道用戶對框的操作
調用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
}
}