【发布时间】:2021-04-24 04:38:33
【问题描述】:
我目前正在关注本指南https://developer.android.com/training/camera/photobasics#TaskPath。
我正在尝试拍摄照片并将其添加到我的画廊,但每当我拍摄照片时,没有任何内容添加到画廊或应该存储照片的 SD 卡中。这是我用 Java 编写的使用相机拍照的代码。
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
galleryAddPic();
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
我认为在此处生成 URI 时出现了问题,或者意图没有正确放置额外内容。有什么建议可以解决吗?
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
【问题讨论】:
-
但是图像文件是从一开始就创建的吗? (不要使用图库检查)。如果它在那里并且文件大小为零,那么您可以使用 file.createTempFIle() 来执行此操作。话虽如此,我必须补充一点,你遵循了一个可怕的例子,因为你不应该创建一个大小为 0 的临时文件。您唯一需要的是一个 uri。
-
我查看了模拟器上的外部存储,但那里也没有保存文件。除了检查模拟器存储之外,我如何检查文件是否正确创建和存储?
-
try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File }如果没有异常,则文件已创建,您可以使用模拟器上的任何文件资源管理器/管理器找到它。 -
您还应该在相机意图上放置一个授权写入标志。相机启动了吗?
-
我也尝试重新启动应用程序,但在它应该保存的文件夹中也没有发现任何文件。
标签: java android android-studio android-camera uri