1

我正在使用下载管理器下载文件,如下所示:

   DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle(createTitle());
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalFilesDir(activity, Environment.DIRECTORY_DOWNLOADS, subFolders + createFileName());
    request.allowScanningByMediaScanner();

下载后,我将其添加到媒体商店,如下所示:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    ContentValues contentValues = new ContentValues();
                    ContentResolver database = activity.getContentResolver();

                    contentValues.put(MediaStore.Downloads.DISPLAY_NAME, displayName);
                    contentValues.put(MediaStore.Downloads.MIME_TYPE, mimeType);
                    contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/subfolder");
                    database.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
                }

我将看到在图库中创建的文件夹,但该文件始终显示为已损坏。任何人都可以帮忙吗?

4

1 回答 1

1

为了能够在图库中加载或查看您下载的图像,您需要使用 MediaScannerConnection 扫描保存的文件:

private void scanFile(String path) {

    MediaScannerConnection.scanFile(context,
            new String[] { path }, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                public void onScanCompleted(String path, Uri uri) {
                    Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
                }
            });
}

在创建文件路径或检查文件是否存在后调用它:

scanFile(filePath);

希望它会工作:)

于 2020-10-07T13:22:24.260 回答