当超过targetSdkVersion>=23时,软件打开相机都需要 安卓权限
安卓系统相机权限访问
1.导入PermissionUtils工具包库 在app的build.gradle的依赖中导入
dependencies {
implementation 'com.blankj:utilcode:1.25.9'
}
如下:
2.使用util包
private void startPreviewWithPermission() {
PermissionUtils.permission(PermissionConstants.CAMERA)
.callback(new PermissionUtils.SimpleCallback() {
@Override
public void onGranted() {
try {
Toast.makeText(MainActivity.this, "相机授权申请成功", Toast.LENGTH_SHORT).show();
...
} catch (Exception ignored) {
Toast.makeText(MainActivity.this, "相机授权申请报错", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDenied() {
Toast.makeText(MainActivity.this, "相机授权申请否决", Toast.LENGTH_SHORT).show();
}
}).request();
}
3.操作截图 3.1 初始页面
3.2 相机授权弹窗
3.3 相机权限申请成功
代码亲测例子参考: 说明:通过button id为key_type_button_camera进行监听,点击后申请相机权限,callback函数中操作 (当权限申请成功后,再次调用该方法直接会进入onGranted()方法)
public class MainActivity extends AppCompatActivity {
static final int REQUEST_CODE_LIVENESS = 1000;
private static final int PERMISSIONS_REQUEST_CODE = 1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.key_type_button_camera).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "相机授权", Toast.LENGTH_SHORT).show();
startPreviewWithPermission();
}
});
}
private void startPreviewWithPermission() {
PermissionUtils.permission(PermissionConstants.CAMERA)
.callback(new PermissionUtils.SimpleCallback() {
@Override
public void onGranted() {
try {
Toast.makeText(MainActivity.this, "相机授权申请成功", Toast.LENGTH_SHORT).show();
...
} catch (Exception ignored) {
Toast.makeText(MainActivity.this, "相机授权申请报错", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDenied() {
Toast.makeText(MainActivity.this, "相机授权申请否决", Toast.LENGTH_SHORT).show();
}
}).request();
}
}
参考链接: https://blankj.com/
|