gpt4 book ai didi

Android IMAGE_CAPTURE Intent 在 onActivityResult 之后保存照片

转载 作者:行者123 更新时间:2023-11-30 01:50:03 25 4
gpt4 key购买 nike

我正在尝试使用 IMAGE_CAPTURE Intent 拍照并立即在屏幕上显示这张照片。我的工作:

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 Activity 在后台将图像保存到文件中,并且我的 onActivityResult 在保存图像之前 被执行。因此,我的 photo == null。虽然如果我在 BitmapFactory.decodeFile 调用之前放置断点它会起作用。我用一个丑陋的 hack 修复了它:

while (photo == null) {
photo = BitmapFactory.decodeFile(mPhotoPath);
}

那么,我做错了什么吗?为什么会这样?

我正在 Marshmallow Nexus 5 上进行测试。

最佳答案

Apparently IMAGE_CAPTURE activity saves image to a file in background and my onActivityResult gets executed before image is saved

我认为这是处理您的请求的特定相机应用程序中的错误。有成百上千个这样的相机应用程序,像这样的错误在某种程度上很常见。

I fixed it with an ugly hack

像这样的繁忙循环从来都不是一个好主意。除其他事项外,如果在主应用程序线程中完成,它会卡住您的 UI,即使在后台线程中完成,它也会严重消耗 CPU。

我会尝试 a FileObserver监视文件何时关闭,以更加事件驱动。如果出于某种原因,您无法使其正常工作:

  • 确保您在后台线程中执行监视文件逻辑
  • 在两次尝试之间添加合理的 SystemClock.sleep() 周期(例如 50 毫秒)

关于Android IMAGE_CAPTURE Intent 在 onActivityResult 之后保存照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33187681/

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