参阅Android Developer: https://developer.android.com/training/permissions/requesting.html#perm-request
运行时权限
从Android 6.0(API level 23)开始,用户需要在App运行的时候授予某些权限,而并非安装时。Android的系统权限分为两种:
- Normal permissons. 这列权限只需要在Androidmanifest文件中列出既可,系统会自动授予这些权限。
- Dangerous permissions. 这类权限由于涉及到用户的隐私,所以不仅需要在Androidmanifest文件中列出,还需要在App运行时由用户授予。后文中的权限都指此类权限。文章的最后会列出哪些权限属于Dangerous permissions.
具体操作
检查权限
如果你的App的某项操作需要用到某项权限,你首先需要检查你的APP是否已经被授予了该权限,调用ContextCompat.checkSelfPermission()方法即可。示例代码如下:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR);
该方法会返回一个Int类型的值,当返回值等于 PackageManager.PERMISSION_GRANTED时表示你已经获得了该权限;当返回值等于PERMISSION_DENIED时,表示还未获得该权限,需要用户授予。
获得权限
有些情况下,你可能会需要向用户解释为什么需要获得该权限。那么什么时候向用户解释呢,Android提供了shouldShowRequestPermissionRationale()方法,当其返回true的时候,表明你应该向用户解释你需要该权限的原因,如果返回false,则不需要。
接下来就是调用requestPermissions()方法来申请权限。示例代码如下
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// 是否该向用户解释
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// 向用户解释原因
} else {
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.
}
}
处理申请权限的结果
当App申请权限的时候,系统会弹出一个Dialog(该Dialog不可自定义)。用户选择以后,会触发onRequestPermissionsResult() 方法,我们会在该方法里处理用户选择的结果。具体代码如下:
@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;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Dangerous permissions and permission groups
Permission Group | Permissions |
---|---|
CALENDAR | READ_CALENDAR, WRITE_CALENDAR |
CAMERA | CAMERA |
CONTACTS | READ_CONTACTS, WRITE_CONTACTS, GET_ACCOUNTS |
LOCATION | ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION |
MICROPHONE | RECORD_AUDIO |
PHONE | READ_PHONE_STATE, CALL_PHONE, READ_CALL_LOG, WRITE_CALL_LOG, ADD_VOICEMAIL, USE_SIP, PROCESS_OUTGOING_CALLS |
SENSORS | BODY_SENSORS |
SMS | SEND_SMS, RECEIVE_SMS, READ_SMS, RECEIVE_WAP_PUSH, RECEIVE_MMS |
STORAGE | READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE |