在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只需要調用相應的方法即可。