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

时间:2015-06-30 19:43:30

标签: android android-mediascanner storage-access-framework

我正在使用存储访问框架将图像下载到外部SD卡。问题是这些图像没有出现在图库中。我试图通过发送DocumentFile uri来通知Android媒体扫描程序,但这并不能解决问题。以下是我尝试通知媒体扫描程序添加了新图像的方法:

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

是否有其他方式通知Android添加了新图片? (我已经尝试了here描述的方法,但我无法使用这些方法获得真正的路径)

1 个答案:

答案 0 :(得分:1)

我现在找到了解决方案。我正在使用以下方法从DocumentFile获取文件路径。将此路径发送到媒体扫描程序时,文件将被正确扫描:

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;
}