startActivityForResult
和權限請求可以結合使用,以便在啟動新活動之前檢查并請求必要的權限。以下是一個簡單的示例,說明如何實現這種結合:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
private static final int REQUEST_CODE_PERMISSIONS = 100;
private void launchActivityWithPermissionCheck() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSIONS);
} else {
launchActivity();
}
}
launchActivity()
方法以啟動新活動:private void launchActivity() {
Intent intent = new Intent(this, TargetActivity.class);
startActivityForResult(intent, REQUEST_CODE_PERMISSIONS);
}
onRequestPermissionsResult()
方法以處理權限請求結果:@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, you can launch the activity now
launchActivity();
} else {
// Permission denied, inform the user
Toast.makeText(this, "Camera permission is required to launch the target activity", Toast.LENGTH_SHORT).show();
}
}
}
TargetActivity
中處理結果,并將結果返回給啟動它的活動:@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PERMISSIONS && resultCode == RESULT_OK) {
// Permission granted, you can process the result now
// ...
} else {
// Permission denied or activity finished, inform the caller activity
setResult(RESULT_CANCELED);
finish();
}
}
現在,在啟動TargetActivity
之前,系統會檢查并請求相機權限。如果用戶授權了權限,活動將正常啟動;否則,將顯示一條消息通知用戶需要權限。