TamarG TamarG - 2 months ago 11x
Android Question

Open a downloaded file after downloading in 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);

// Notify user when download is completed
// (Seems to be available since Honeycomb only)

// Start download
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

else {
// ....


How can I add a code to open the file after the downloading is done?


Add this BroadcastReceiver to your code and launch and intent with the uri.

    BroadcastReceiver receiver = new BroadcastReceiver() {
        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();
                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