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

Open a downloaded file after downloading in Android

我有一个应用程序,其中包含指向 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 启动和意图。

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