在AndroidManifest.xml中添加:
动态权限添加:
在onCreate中添加
//调取系统照相机
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!=
PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
wxat = 200;
}
方法:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
wxat = 200;
} else {
Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
}
}
}
或者使用easypermissions框架 (https://github.com/googlesamples/easypermissions)
1、首先也是在AndroidManifest.xml中添加:
2、在主页面中:
2.1、初始化集合装载所需网络权限
private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
2.2、检查权限申请权限
//获取权限
private void getPermission() {
if (EasyPermissions.hasPermissions(this, permissions)) {
//已经打开权限
Toast.makeText(this, "已经申请相关权限", Toast.LENGTH_SHORT).show();
} else {
//没有打开相关权限、申请权限
EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
}
}
2.3、实现接口
在所运用权限申请的界面实现EasyPermissions.PermissionCallbacks接口
2.4、处理接口回调的数据
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//框架要求必须这么写
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
//成功打开权限
@Override
public void onPermissionsGranted(int requestCode, @NonNull List perms) {
Toast.makeText(this, "相关权限获取成功", Toast.LENGTH_SHORT).show();
}
//用户未同意权限
@Override
public void onPermissionsDenied(int requestCode, @NonNull List perms) {
Toast.makeText(this, "请同意相关权限,否则功能无法使用", Toast.LENGTH_SHORT).show();
}