![](/img/trans.png)
[英]How to get the network uri of a file being downloaded from the Download Manager in Android
[英]How to get yhe URI of a file that I downloaded with download manager?
我使用下載管理器下載 .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 IS HERE )。 因此,您必須“存儲”該 id 以供將來操作(例如查閱下載文件的 Uri)。
這樣,如果使用Uri getUriForDownloadedFile(long id);
成功下載文件,則可以使用該 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 id = 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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.