在安卓设备中下载文件后如何打开下载的文件

8

我有一个应用程序,其中包含一些指向网络文件的链接。我希望用户选择下载文件后,该文件能够自动打开。 以下是我的下载代码:

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 {
            // ....
        }

    }

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

1
这个很好用。 - srijanshukla
1个回答

11

将此BroadcastReceiver添加到您的代码中,并使用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'声明为长整型。
 enq=dm.enqueue(r);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接