Android: Download a file with progress indication

The following example shows you how to:

  • download a file
  • display the progress in a progress dialog
  • use AsyncTask
  • create a temporary file

tumblr_lnmev5uOLt1qly6u1o1_400
Like a BOSS

I've used this code in my app Moustachify Everything. Initially, the app didn't display the progress bar and it was annoying because you never know if it was actually doing anything.

it's a bit lengthy, but I assure you it's worth it for the user once you see it in action.

/**
* Downloads file from URL and does something with it.
*/
private void downloadFile(String url) {
final ProgressDialog progressDialog = new ProgressDialog(this);

new AsyncTask() {
private Exception m_error = null;

@Override
protected void onPreExecute() {
progressDialog.setMessage("Downloading ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

progressDialog.show();
}

@Override
protected File doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection;
InputStream inputStream;
int totalSize;
int downloadedSize;
byte[] buffer;
int bufferLength;

File file = null;
FileOutputStream fos = null;

try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

file = File.createTempFile("Mustachify", "download");
fos = new FileOutputStream(file);
inputStream = urlConnection.getInputStream();

totalSize = urlConnection.getContentLength();
downloadedSize = 0;

buffer = new byte[1024];
bufferLength = 0;

// Read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress(downloadedSize, totalSize);
}

fos.close();
inputStream.close();

return file;
}
catch (MalformedURLException e) {
e.printStackTrace();
m_error = e;
}
catch (IOException e) {
e.printStackTrace();
m_error = e;
}

return null;
}

protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
};

@Override
protected void onPostExecute(File file) {
// If there was an error, do something informative with it.
if (m_error != null) {
m_error.printStackTrace();
return;
}

progressDialog.hide();

// You probably want to do something else with this
file.delete();
}
}.execute(url);
}

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog