如何获取我使用下载管理器下载的文件的 URI?

问题描述 投票:0回答:1

我使用下载管理器下载.ogg 文件。 我用这个代码下载它:

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setDescription(list.get(position).getName());
            request.setTitle(list.get(position).getName());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, list.get(position).getName() + ".ogg");

            DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);

现在我想分享这个文件,所以我需要他的 uri。

如何获取这个文件uri?

android uri
1个回答
5
投票

方法

DownloadManager.enqueue()
返回一个Id(DOC IS HERE)。因此,您必须“存储”该 id 以供将来操作(例如查阅下载文件的 Uri)。

这样,如果使用

Uri
DOC HERE
成功下载文件,您可以使用该 ID 来获取 Uri getUriForDownloadedFile(long id);

编辑

如果您创建了

BroadcastReceiver
来接收有关已完成下载的广播,您可以在文件下载后立即获取 Uri:

private int mFileDownloadedId = -1;

// Requesting the download
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
mFileDownloadedId = manager.enqueue(request);

// Later, when you receive the broadcast about download completed.
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       long downloadedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
       if (downloadedID == mFileDownloadedId) {
           // File received
           DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
           Uri uri = manager.getUriForDownloadedFile(mFileDownloadedId);
       }
    }
}

@Override
public void onResume() {
    super.onResume();

    registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

@Override
public void onPause() {
    super.onPause();
    // Don't forget to unregister the Broadcast
}
© www.soinside.com 2019 - 2024. All rights reserved.