简体   繁体   English

Android 存储访问框架和媒体扫描器

[英]Android storage access framework and media scanner

I'am using the storage access framework to download images to the external sd card.我正在使用存储访问框架将图像下载到外部 SD 卡。 The problem is that these images do not appear in the gallery.问题是这些图像没有出现在图库中。 I've tried to inform the Android media scanner using an intent by sending the DocumentFile uri, but that doesn't seam to work.我尝试通过发送 DocumentFile uri 使用意图通知 Android 媒体扫描仪,但这并不起作用。 Here is how I try to inform the media scanner that a new image is added:以下是我尝试通知媒体扫描仪添加了新图像的方法:

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(documentFile.getUri());
sendBroadcast(intent);

Is there another way to inform Android that a new image was added?是否有另一种方法可以通知 Android 添加了新图像? (I've already tried the methods described here , but I couldn't get the real path using those methods) (我已经尝试过这里描述的方法,但我无法使用这些方法获得真正的路径)

I've now found a solution.我现在找到了解决办法。 I'am using the following method to get the file path from the DocumentFile.我正在使用以下方法从 DocumentFile 获取文件路径。 When sending this path to the media scanner the file is scanned correctly:将此路径发送到媒体扫描仪时,文件将被正确扫描:

private static Object[] volumes;

public static Uri getDocumentFileRealPath(Context context, DocumentFile documentFile) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    final String docId = DocumentsContract.getDocumentId(documentFile.getUri());
    final String[] split = docId.split(":");
    final String type = split[0];

    if (type.equalsIgnoreCase("primary")) {
        File file = new File (Environment.getExternalStorageDirectory(), split[1]);
        return Uri.fromFile(file);
    } else {
        if (volumes == null) {
            StorageManager sm=(StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumeListMethod = sm.getClass().getMethod("getVolumeList", new Class[0]);
            volumes = (Object[])getVolumeListMethod.invoke(sm);
        }

        for (Object volume : volumes) {
            Method getUuidMethod = volume.getClass().getMethod("getUuid", new Class[0]);
            String uuid = (String)getUuidMethod.invoke(volume);

            if (uuid != null && uuid.equalsIgnoreCase(type))
            {
                Method getPathMethod = volume.getClass().getMethod("getPath", new Class[0]);
                String path = (String)getPathMethod.invoke(volume);
                File file = new File (path, split[1]);
                return Uri.fromFile(file);
            }
        }
    }

    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM