gpt4 book ai didi

Android:使用ActivityResultLauncher时如何区分多个 Intent

转载 作者:行者123 更新时间:2023-12-05 00:01:46 25 4
gpt4 key购买 nike

我正在创建一个 Intent 选择器以在手机相机应用和图库/文件管理器之间进行选择。

Intent chooserIntent = Intent.createChooser(clickPhoto(),"Set Image Using");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,openGallery());
startActivityForResult.launch(chooserIntent);

点击拍照方法:

private Intent clickPhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ComponentName componentName = takePictureIntent.resolveActivity(requireActivity().getPackageManager());
if (componentName != null) {
try {
createImageFile();
mimeType = "image/*";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, getNewFileName());
values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
values.put(MediaStore.Images.Media.RELATIVE_PATH, getImageDirectoryPath());

Uri imageUri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL), values);
if (imageUri != null) {
currentPhotoPath = imageUri.toString();
shareUri = imageUri;
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

// initRequestCode(takePictureIntent, requestCode);
} catch (IOException ioException) {
Toast.makeText(requireContext(), ioException.getMessage().toString(), Toast.LENGTH_LONG).show();

}

}
return takePictureIntent;
}

打开图库方法:

private Intent openGallery(){
mimeType = "image/*";
Intent intent = new Intent();
Uri collection = MediaStore.Video.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL);

try {
intent =
new Intent(Intent.ACTION_PICK, collection).setType(mimeType);
intent.resolveActivity(requireActivity().getPackageManager());

// initRequestCode(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(requireContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
return intent;
}

ActivityResultLauncher:

ActivityResultLauncher<Intent> startActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
//how to tell which intent the user selected ?
}
});

我如何知道用户是使用相机拍摄的照片还是使用文件选择器选择的图像?

最佳答案

你可以在返回它们之前为每个 Intent 添加一个额外的整数,你可以在结果中访问它们,比如:

全局变量

   final String SOURCE = "source";
final int SOURCE_CAMERA = 0;
final int SOURCE_GALLERY = 1;
final int SOURCE_UNKNOWN = 2;

相机

...
takePictureIntent.putExtra(SOURCE, SOURCE_CAMERA);
return takePictureIntent;

画廊

..
intent.putExtra(SOURCE, SOURCE_GALLERY);
return intent;

Activity 结果启动器

if (result.getResultCode() == Activity.RESULT_OK) {
//Identify source
int mySource = result.getData().getIntExtra(SOURCE, SOURCE_UNKNOWN )
}

关于Android:使用ActivityResultLauncher时如何区分多个 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72729119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com