一:Android 6.0權限機制的基本介紹
6.0以下的權限: 在安裝的時候,根據(jù)權限聲明產(chǎn)生一個權限列表,用戶只有在同意之后才能完成app的安裝梢为。
6.0以上的權限: 可以直接安裝莺奸,當App需要我們授予不恰當?shù)臋嘞薜臅r候,我們可以予以拒絕统抬。
新的權限機制(6.0以上的權限)的兩種類別
Normal Permissions: 這類權限一般不涉及用戶隱私火本,是不需要用戶進行授權的。
Dangerous Permission: 涉及到用戶隱私的聪建,需要用戶進行授權
Dangerous Permission分組權限機制所帶來的影響: 假設你的APP早已被用戶授權了同一組的某個危險權限钙畔,那么系統(tǒng)會立即授權,而不需要用戶去點擊授權金麸。比如你的APP對READ_CONTACTS已經(jīng)授權了擎析,當你的app申請WRITE_CONTACTS時,系統(tǒng)會直接授權通過钱骂。此外叔锐,對于申請時彈出的dialog上面的文本說明也是對整個權限組的說明,而不是單個權限
基本API及使用
1 在AndroidManifest文件中添加需要的權限
2 檢查權限
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
}else{
//
}
3 申請授權
@Override
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;
}
}
}
二:特殊API
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.
}
這個API主要用于給用戶一個申請權限的解釋见秽,該方法只有在用戶在上一次已經(jīng)拒絕過你的這個權限申請愉烙。也就是說,用戶已經(jīng)拒絕一次了解取,你又彈個授權框步责,你需要給用戶一個解釋,為什么要授權,則使用該方法蔓肯。
總流程
// 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.
}
}