安卓:拍摄的照片未在相册中显示(媒体扫描器意图无效)

8

我有以下问题:我正在开发一个应用程序,用户可以拍照(以附加到帖子),并将照片保存到外部存储。我希望这张照片也会出现在图片库中,并且我正在使用媒体扫描器意图来实现,但似乎没有起作��。在编写代码时,我遵循了官方的Android开发者指南,所以不知道出了什么问题。

我的代码部分:

用于拍摄图像的意图:

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(getActivity().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
            Toast.makeText(getActivity(), ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            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 = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

在视图中显示图片:

private void setPic() {
    // Get the dimensions of the View
    int targetW = 60;
    int targetH = 100;

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    img_added.setImageBitmap(bitmap);
}

广播媒体扫描器意图,使图像在图库中显示:
private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    getActivity().sendBroadcast(mediaScanIntent);
}

在图像捕获意图返回后运行的代码:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        setPic();

        galleryAddPic();
    }
}

我还尝试使用Intent.ACTION_MEDIA_MOUNTED而不是Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,但在这种情况下,我得到了一个“权限被拒绝”的错误。当我记录传递给意图的URI时,我得到了file:///storage/emulated/0/Pictures/JPEG_20150803_104122_-1534770215.jpg,这应该没问题。除此之外,其他所有操作都正常(捕获图像、将其保存到外部存储器并在视图中显示),所以我真的不知道出了什么问题。有人有任何想法吗?提前致谢!
4个回答

14

这取决于这个设备中相册的实现方式。流行的照片应用程序会接收Intent.ACTION_MEDIA_SCANNER_SCAN_FILE广播,但有些只会监听Android媒体数据库。

另外,您还可以同时将图片手动插入到MediaStore中。

public final void notifyMediaStoreScanner(final File file) {
        try {
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                    file.getAbsolutePath(), file.getName(), null);
            mContext.sendBroadcast(new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

另外,请确保您的照片不在私有文件夹中,例如内部存储或使用Context.MODE_PRIVATE进行写入。否则,其他应用程序将没有权限访问此文件。


你的回答是正确的,帮了我很多。我还建议检查mediaScanIntent.resolveActivity的结果。如果为null,则直接将图像插入到MediaStore中,否则调用sendBroadcast方法。 - Uranus

2

在Android中,如果您从应用程序中捕获或添加SD卡或其他设备中的图像。

有时候它不会立即显示在相册中。

如果您捕获并等待一段时间,直到同步过程完成,您将能够看到它。

您可能无法立即看到。


你检查过那个文件夹中是否创建了 .nomedia 文件了吗? - Vatsal Shah

0
在我的情况下,它默默地失败了,因为我在清单中拥有两个权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

你只需要WRITE_EXTERNAL_STORAGE权限。其余的代码来自文档,不需要进行任何修改,但是请检查其他答案以确定原因是否不同。


0

尝试以下代码

private void scanGallery(final Context cntx, String path) {
    try {
        MediaScannerConnection.scanFile(cntx, new String[] { path },null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
            //unimplemeted method
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这里的 imagePath 是捕获图像的完整路径


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接