在Android中,权限请求通常通过运行时权限请求。BaseActivity可以处理权限请求的逻辑如下:
public boolean checkPermission(String permission) {
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
public void requestPermission(String permission, int requestCode) {
ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被授予
onPermissionGranted(requestCode);
} else {
// 权限被拒绝
onPermissionDenied(requestCode);
}
}
public void onPermissionGranted(int requestCode) {
// 处理权限被授予的逻辑
}
public void onPermissionDenied(int requestCode) {
// 处理权限被拒绝的逻辑
}
if (!checkPermission(Manifest.permission.CAMERA)) {
requestPermission(Manifest.permission.CAMERA, REQUEST_CAMERA_PERMISSION);
}
这样,BaseActivity可以处理权限请求的逻辑,并且具体的Activity只需要调用相应的方法即可。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: android进程和线程的区别是什么