【发布时间】:2015-10-17 14:24:55
【问题描述】:
我正在尝试使用 IMAGE_CAPTURE 意图拍照并立即在屏幕上显示这张照片。我做什么:
File photoFile = createImageFile();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, REQUEST_CAMERA);
创建图片文件方法:
private File createImageFile() {
File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoFile = null;
try {
photoFile = File.createTempFile("photo", ".jpg", dir);
mPhotoPath = photoFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return photoFile;
}
当onActivityResult 被调用时,我执行:
Bitmap photo = BitmapFactory.decodeFile(mPhotoPath);
mPhoto.setImageBitmap(photo);
这是一个问题。显然 IMAGE_CAPTURE 活动将图像保存到后台文件中,并且我的onActivityResult 被执行之前图像被保存。因此我的photo == null。虽然如果我在BitmapFactory.decodeFile 调用之前放置断点,它会起作用。我用一个丑陋的 hack 修复了它:
while (photo == null) {
photo = BitmapFactory.decodeFile(mPhotoPath);
}
那么,我做错了吗?为什么会这样?
我正在 Marshmallow Nexus 5 上进行测试。
【问题讨论】:
-
使用
onSaveInstanceState()和onRestoreInstanceState保存文件路径。请参阅此SO Answer。
标签: android android-intent android-image-capture