盒子
盒子

Android动态申请权限

Manifest.permission

Android6.0后,当权限等级为dangerous及以上时,就需要动态权限申请,否则会程序崩溃

打开摄像头示例:

摄像头权限等级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
//在Activity中
//ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
//在Fragment中
}else{
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PhotoFragment.REQUEST_CAMERA) {
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
} else {
Toast.makeText(getActivity(), "未获取打开摄像头权限", Toast.LENGTH_LONG).show();
}
}
}
支持一下
扫一扫,支持Grooter
  • 微信扫一扫
  • 支付宝扫一扫