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?
If a file won't open, a few things could be wrong: You don't have permission to view the file. You're signed in to a Google Account that doesn't have access. The correct app isn't installed on your phone.
Sometimes, corrupted system files or bad sectors on Windows system drive may cause hard drives, folders, or files inaccessible. Therefore, fixing corrupted system files and repair bad sectors on the hard drive may help you fix the Downloads folder that won't open error.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With