我正在尝试使用IMAGE_CAPTURE意图拍照并立即在屏幕上显示此照片。我做什么:Android IMAGE_CAPTURE意图在onActivityResult后保存照片
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
呼叫之前放置断点,它也可以工作。我用一个丑陋的黑客修复它:
while (photo == null) {
photo = BitmapFactory.decodeFile(mPhotoPath);
}
所以,我做错了什么?为什么它以这种方式工作?
我对棉花糖的Nexus测试5.
使用'onSaveInstanceState()'和'onRestoreInstanceState'来保存文件路径。请参阅此[SO答案](http://stackoverflow.com/a/32723550/3140227)。 –