在Android下载后打开下载的文件

时间:2016-07-31 17:33:30

标签: android file android-download-manager

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

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 个答案:

答案 0 :(得分:8)

将此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);