gpt4 book ai didi

android - 在 Android 中下载后打开下载的文件

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:34 25 4
gpt4 key购买 nike

我有一个应用程序,其中包含指向 Web 上文件的一些链接。我希望在用户选择将文件下载到设备后 - 该文件将自动打开。这是我的下载代码:

private void downloadFile(String url) {

if (GeneralHelper.isNetworkAvailable(this)) {
Uri uri = Uri.parse(url);
DownloadManager.Request r = new DownloadManager.Request(uri);

String fileName = url.substring( url.lastIndexOf('/')+ 1, url.length() );

// This put the download in the same Download dir the browser uses
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
r.allowScanningByMediaScanner();

// Notify user when download is completed
// (Seems to be available since Honeycomb only)
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

// Start download
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);

}
else {
// ....
}

}

下载完成后如何添加打开文件的代码?

最佳答案

将此 BroadcastReceiver 添加到您的代码并使用 uri 启动和 Intent 。

    BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enq);
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//TODO : Use this local uri and launch intent to open file

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

开始下载时,进行以下更改,将'enq'声明为long类型

 enq=dm.enqueue(r);

关于android - 在 Android 中下载后打开下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38686681/

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