1.运行时权限
以下权限需要进行运行时权限处理:
权限组名 | 权限名 |
---|---|
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_EXYERNAL_STORAGE |
以CALL_PHONE为例,进行运行时权限申请:
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CALL_PHONE}, 1);
else{
XXXXXXXX
}
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == packageManager.PERMISSION_GRANTED) {
XXXXXXXXX;
}
}
}
第一步先要判断用户是不是已经授权了,借助的是ContextCompat.checkSelfPermission()方法。checkSelfPermission()方法接受两个参数,第一个参数是Context,第二个参数是具体的权限名。然后使用方法的返回值和PackageManager.PERMISSION_GRANTED做比较,相等就说明用户已经授权,不等就表示用户没有授权。
如果没有授权的话,则需要调用ActivityCompat.requestPermissions()方法来向用户申请授权。requestPermission()方法接收3个参数,第一个参数要求是Activity的实例,第二个参数是一个string数组,用来放申请的权限名,第三个参数是请求码。
之后,系统会弹出一个权限申请的对话框,然后用户同意或拒接权限申请。最后会回调onRequestPermissionResult()方法,授权的结果封装在grantResults参数中。
网友评论