Android Series: Download files with Progress Dialog
Today, I will present a short tutorial on how to download files in android displaying at the same time download progress based on the bytes downloaded. For the purpose of this tutorial we will use build in AsyncTask mechanism together with ProgressDialog class.
The whole application consists of one activity displaying a ‘Start Download’ button. Clicking our start button we initialize file download passing to the asynctask the url or the resource we want to download.
package com.softwarepassion;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndroAsync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndroAsync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
layout file (main.xml) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="Start long running task.."
android:id="@+id/startBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="Start long running task.."
android:id="@+id/startBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
While downloadin a file from the internet remember to add INTERNET permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Check your sd card folder for what was downloaded and enjoy!
thanks for posting this code, however i’m unable to get it working. in my DownloadFileAsync class, i get an error with showDialog and dismissDialog. any ideas?
nm that last comment. i just decided to put all the code in one class file and it worked like a charm. thanks again!
Hi, thanks for this post. I was able to run this code successfully.
However, I’m having one problem. Instead of images I’m trying to use this to download multiple video files. I’m using a for loop inside startDownload() method to iterate the URLs from an array.
But when the video size increases to 7-8 MB the application crashes. Any thoughts ?
Thanks! It’s very simple.
thanks for this code!
but i don’t get it working.
By pressing on the button it only says downloading for about a second, but the bar is not getting fuller.
the file will not be downloaded 🙁
any ideas?
i’ve got the same problem as Luhu. please help us!
Cannot help you with the amount of information given, you would have to be more precise, try to debug it or if you cannot debug it yourself and still have no idea whats goin’ on just send me a link to your eclipse project for me to download.
I exactly copied what you said and it just don’t work.
And if I debug it, it don’t say there’s something wrong.
Why,When i debug this program in Onupdate it not go to it.
Because my app show dialog but progress bar not active.
Hi, thanx a lot for the code, it works great!!
Love havin the progressbar…
Just 2 questions:
1.)
How would I go about making a second button, to download another file in the AndroAsync.java ?
(xml.file is clear, just the .java not 🙂 )
2.)
How can use this code to create sub-folder in SD Card,?
Thanx a lot in advance!
Doesn’t run under Android 1.5.
To those that are commenting that it is not working, you need an additional 2 lines of code in the AndroidManifest for permission of reading/writing to the SD card:
“android.permission.WRITE_EXTERNAL_STORAGE”
“android.permission.READ_EXTERNAL_STORAGE”
It didn’t show up on previous post, sorry.
Great Tutorial !
Thank you alot 🙂
Having the same problem as the 2 guys above.
07-14 14:25:08.600: WARN/InputManagerService(126): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@40a54038
The Dialog pops up for like 0.1s and then disappears.
thanks for your tuto!!!
It’s so good
Thanx for posting this code but it is not working properly.Progress dialog appears only for one second and disappears and nothing is downloaded.Please help me
Thanx
Thanks for the post. Nice code….
i want to download in my assests folder what output path should be declare??
I too got the same problem , nothing downloading , Jus progress bar appears and disappears .
doInBackground(String… aurl)
try{
…..//not comes with try
}
catch{
//program comes here
}
Check that your emulator has some storage space assigned to it, if not it will throw an error and behave like you have described..
Hi, If i want to download video then is this the same code we need to write?
I use this code but dialog box close after some time and no download happened.
what should i write here if i use video download..
OutputStream output = new FileOutputStream(“/sdcard/some_photo_from_gdansk_poland.jpg”);
Please help me ..
Thanks and Regards,
Anoop
I did it nd it works fine………But just wanted to know “How do i display that particular filename on progress dialog?”
Can it be possible??
Plz help in this issue….
How do I implement a cancel download option in this program?
hi could u tel me how to download a file using service if possible plzzzzzzzzzzzzzzzzz
This code is very useful.but when i download xlsx file it displays as binary format can you solve this problem?