gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:14:46 26 4
gpt4 key购买 nike

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

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

编辑

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

关于android - 如何获取我使用下载管理器下载的文件的 URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com