在Android中下载后打开下载的文件 [英] Open a downloaded file after downloading in Android
本文介绍了在Android中下载后打开下载的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,该应用程序带有一些指向网络上文件的链接.我希望在用户选择将文件下载到设备后-该文件将自动打开.这是我的下载代码:
I have an app with some links to files on the web. I want that after the user choose to download a file to the device - the file will be opened automatically. This is my code for downloading:
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 {
// ....
}
}
下载完成后,如何添加代码以打开文件?
How can I add a code to open the file after the downloading is done?
推荐答案
将此BroadcastReceiver添加到您的代码中,并使用uri启动和使用.
Add this BroadcastReceiver to your code and launch and intent with the uri.
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'声明为长类型
When you start the download, make the following change, declare 'enq' as long type
enq=dm.enqueue(r);
这篇关于在Android中下载后打开下载的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文