我正在使用 registerForActivityResult 用于发射相机或图库,但 registerForActivityResult 能够像Intent.ACTION_CHOOSER一样吗?
cameraLauncher =
registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
if (success) {
// do somthing
}
}
galleryLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) {
// do somthing
}
以旧的方式
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE)
galleryIntent.type = "image/*"
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val chooserIntent = Intent(Intent.ACTION_CHOOSER)
chooserIntent.putExtra(Intent.EXTRA_INTENT, galleryIntent)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent))
startActivity(chooserIntent)
我确实通过实现ActivityResultContracts.StartActivityForResult()
来使其工作,该使用与 so 相同的参数调用现有onActivityResult
(Java 中的示例):
ActivityResultLauncher<Intent> activityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
YourActivity.this.onActivityResult(PICK_IMAGE_ID, result.getResultCode(), result.getData());
}
});
然后你只需按以下方式开始它:
Intent pickIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
Intent chooserIntent = Intent.createChooser(pickIntent, "Choose");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{takePhotoIntent});
if(SDK_INT > Build.VERSION_CODES.Q) {
activityForResult.launch(chooserIntent);
} else {
//support for older than android 11
startActivityForResult(chooserIntent, PICK_IMAGE_ID);
}
您的AndroidManifest.xml
还需要以下查询:
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
<intent>
<action android:name="android.intent.action.PICK" />
<data android:mimeType="image/*" />
</intent>
</queries>
请注意,startActivityForResult
和onActivityResult
已弃用,并将在将来的某个时候被删除。