如何将拍摄的照片添加到MediaStore

5

我想将已拍摄的照片添加到MediaStore中,以便图库应用程序可以找到它们(无需重新启动设备)。 应用程序的最小SDK版本是9。任何帮助、博客或文档都将不胜感激。

4个回答

7

在大多数设备上,你只需要等一段时间,新的照片就会自动检测到。

如果你想立即刷新相册,你需要使用MediaScanner类,它将刷新相册 - 删除已删除的照片,添加新的照片等等...

public void refreshGallery() {
    Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    String newPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image
    File file = new File(newPhotoPath);
    Uri contentUri = Uri.fromFile(file);
    scanIntent.setData(contentUri);
    sendBroadcast(scanIntent);
}

希望这有所帮助!

ACTION_MEDIA_SCANNER_SCAN_FILE 替换 ACTION_MEDIA_MOUNTED 解决了问题。请编辑您的答案以便我接受它作为正确答案! - Ali Behzadian Nejad
这对旧版的Android系统可用吗?我有一个运行Android 4.2的平板电脑,在该设备上扫描单个文件无法工作,而在另一个运行Android 4.4的手机上相同的代码可以工作。在Android 4.2上,我可以开始扫描整个SD卡,但不能扫描单个文件。这是Android 4.2的问题还是仅适用于我的A-4.2平板电脑? - k3b
"ACTION_MEDIA_SCANNER_SCAN_FILE"已被弃用。 - Thomas Klammer

1
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

在您的“保存”代码之后插入此行代码。
这将触发媒体扫描,所有文件夹中的所有媒体文件(除了带有“.nomedia”文件的文件夹)都将被更新并在相册中显示。 来源MediaScanner文档
或者:
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
        new String[] { file.toString() }, null,
        new MediaScannerConnection.OnScanCompletedListener() {
    public void onScanCompleted(String path, Uri uri) {
        Log.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
    }
});

Google的示例代码.


这是一个庞大且耗时的过程。我只想添加一个文件! - Ali Behzadian Nejad
我不知道你怎么能简单地添加一个文件。你必须重新扫描整个文件系统,或者等待安卓系统自动为你完成。 - Ab5
我添加了另一种方法,是在developers.android.com上找到的,希望能有所帮助! - Ab5

0

好的,这是我的代码,它对我有效。它会返回所有我在Android图库中看到的图片,只需从此行调用此函数即可。

 getallimages(Environment.getExternalStorageDirectory());

我的函数如下所示

private void getallimages(File dir)
    {

                String[] STAR = { "*" };

        final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
        Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        int count = imagecursor.getCount();
        for (int i = 0; i < count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            ImageItem imageItem = new ImageItem();

            if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
            {
                imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    imageItem.id = id;
                    imageItem.selection = false; //newly added item will be selected by default
                    controller.images.add(imageItem);   

            }
 }

}

0

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