Open a downloaded file after downloading in Android

TamarG picture TamarG · Jul 31, 2016 · Viewed 10.2k times · Source

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?

Answer

srijanshukla picture srijanshukla · Jul 31, 2016

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

When you start the download, make the following change, declare 'enq' as long type

 enq=dm.enqueue(r);