簡體   English   中英

Android 存儲訪問框架和媒體掃描器

[英]Android storage access framework and media scanner

我正在使用存儲訪問框架將圖像下載到外部 SD 卡。 問題是這些圖像沒有出現在圖庫中。 我嘗試通過發送 DocumentFile uri 使用意圖通知 Android 媒體掃描儀,但這並不起作用。 以下是我嘗試通知媒體掃描儀添加了新圖像的方法:

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

是否有另一種方法可以通知 Android 添加了新圖像? (我已經嘗試過這里描述的方法,但我無法使用這些方法獲得真正的路徑)

我現在找到了解決辦法。 我正在使用以下方法從 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM