Android权限获取
在Android 6.0(SDK23)之后,对于危险的权限不仅仅需要在清单文件中标明,还需要在APP运行时,动态的请求权限。
危险权限被分为9组,当程序已经获取了同一组的其他权限时,再次请求同一组的某个权限,系统会立即给予权限,不再需要用户手动确认。权限分组如下所示:
权限组 | 权限名 |
---|---|
CALENDAR | READ_CALENDAR,WRITE_CALENDAR |
CAMERA | CAMERA |
CONTACTS | READ_CONTACTS, |
WRITE_CONTACTS,GET_ACCOUNTS | |
MICROPHONE | RECORD_AUDIO |
PHONE | READ_PHONE_STATE… |
SENSORS | BODY_SENSORS |
SMS | SEND_SMS,RECEIEVE_SMS,READ_SMS |
STORAGE | READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE |
获得权限
想要获得一个权限,首先需要在manifest文件中声明权限,以CAMERA权限举例
<uses-permission android:name="android.permission.CAMERA"/>
然后从应用中申请权限
//判断SDK等级
if (Build.VERSION.SDK_INT > 23){
//判断是否拥有权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED){
//如果没有权限,则申请权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, 1);
}else {
//如果有,则直接打开相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
}else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
当用户同意申请后,我们还需要重写onRequestPermissionsResult方法处理返回的结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
//这里判断用户处理了什么权限,这里的1是我们申请时赋予的requestcode
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
break;
default:
break;
}
}