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



我使用下载管理器下载.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?

方法DownloadManager.enqueue()返回一个Id(DOC在此处(。所以,你必须"存储";该id用于将来的操作(例如查阅下载的文件的Uri(。

这样,如果使用Uri getUriForDownloadedFile(long id);(DOC HERE(成功下载文件,则可以使用该Id获取Uri

编辑

如果您创建了一个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
}