Monday, 30 April 2012

How to Download a File in Android and show its progress in the Progress Dialog

We can implement this in a number of ways and one of the way is using the AsyncTask and show the download progress.
The method is as follows:-

Just make a button and on its onclick event call the below function as :- startDownload();




private void startDownload() {
String url = "WRITE YOUR URL THAT YOU WANT TO DOWNLOAD";
new DownloadFileAsync().execute(url);
}


@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
myProgressDialog = new ProgressDialog(this);
myProgressDialog.setMessage("Downloading the file..");
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(false);
myProgressDialog.show();
return myProgressDialog;
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/yourfilename.extension");

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]);
myProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}


After running this activity you can check your file in the specified location above.

Make sure to give the following permissions in your Manifest File for the proper functioning of the Downloading Activity. i.e :-


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

This is all done about downloading a file and showing its progress.


No comments:

Post a Comment