更新时间:2022-11-20 22:51:08
您可以使用startActivityForResult
,传入一个 Intent 来描述您想要完成的操作以及执行该操作的数据源.
You can usestartActivityForResult
, passing in an Intent that describes an action you want completed and and data source to perform the action on.
幸运的是,Android 包含一个用于挑选东西的 Action:Intent.ACTION__PICK
和一个包含图片的数据源:android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
用于本地设备上的图像或android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
用于 SD 卡上的图像.
Luckily for you, Android includes an Action for picking things: Intent.ACTION__PICK
and a data source containing pictures:
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
for images on the local device or
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
for images on the SD card.
调用 startActivityForResult
传入选择操作和您希望用户从中选择的图像,如下所示:
Call startActivityForResult
passing in the pick action and the images you want the user to select from like this:
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), SELECT_IMAGE);
然后覆盖 onActivityResult
以监听用户进行了选择.
Then override onActivityResult
to listen for the user having made a selection.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
// TODO Do something with the select image URI
}
}
获得图像 Uri 后,您可以使用它来访问图像并执行任何您需要的操作.
Once you have the image Uri you can use it to access the image and do whatever you need to do with it.