[英]Activity results always returns null when asking for picture
我正试图从相机或图库(无论用户选择什么)中获取图像。 问题是我在OnActivityResult
总是将intent.getData()
为null。 我做了以下的建议在这里 :
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });
startActivityForResult(chooserIntent, SELECT_PICTURE);
OnActivityResult:
if (requestCode == SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
final Uri imageUri = data.getData();
Log.e("uri", imageUri + "");
uri为空
好吧, ACTION_IMAGE_CAPTURE
不返回Uri。 但是,如果您真的有机会在使用照片后得到Uri,则需要指定照片的路径(它将照片保存在该路径上,所以这不是临时的)。
这是该示例之一(这将创建目录并为您的图像准备新文件):
// Determine Uri of camera image to save.
File root = new File(
Environment.getExternalStorageDirectory() + File.separator + locationName + File.separator);
root.mkdirs();
String fname = imagePrefixName + System.currentTimeMillis() + ".jpg";
File imageMainDirectory = new File(root, fname);
Uri outputFileUri = Uri.fromFile(imageMainDirectory); //make sure you store this in the place that can be accessed from your onActivityResult
决定outputUri并将其存储后,您需要像这样在相机意图上实现该uri:
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
然后,当您收到数据时,可以执行以下操作来检查图片是否来自图库或相机(所存储的图片上面带有Uri):
final Uri imageUri = data.getData();
if (imageUri == null)
{
imageUri = outputFileUri;
}
确保您实现了对外部存储的读写权限,并且,我想您会获得所需的Uri。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.