Android Series: Download files with Progress Dialog

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.


AndroAsync.java

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);
        }
    }
}

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>

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!

30 responses on “Android Series: Download files with Progress Dialog

  1. Jayson February 21, 2011 at 11:31 am

    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?

  2. Jayson February 21, 2011 at 11:48 am

    nm that last comment. i just decided to put all the code in one class file and it worked like a charm. thanks again!

  3. Dave February 21, 2011 at 3:21 pm

    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 ?

  4. vlodimer April 16, 2011 at 9:59 am

    Thanks! It’s very simple.

  5. luhu April 17, 2011 at 11:07 am

    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?

  6. Robbert April 20, 2011 at 5:36 pm

    i’ve got the same problem as Luhu. please help us!

  7. admin April 20, 2011 at 8:19 pm

    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.

  8. Robbert April 21, 2011 at 2:34 pm

    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.

  9. paisarn May 11, 2011 at 11:12 am

    Why,When i debug this program in Onupdate it not go to it.
    Because my app show dialog but progress bar not active.

  10. roveri May 28, 2011 at 5:40 am

    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!

  11. Polaris431 May 31, 2011 at 10:45 am

    Doesn’t run under Android 1.5.

  12. rL June 2, 2011 at 10:10 pm

    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:

  13. rL June 2, 2011 at 10:16 pm

    “android.permission.WRITE_EXTERNAL_STORAGE”
    “android.permission.READ_EXTERNAL_STORAGE”

    It didn’t show up on previous post, sorry.

  14. Hanan Nimer July 11, 2011 at 12:45 pm

    Great Tutorial !
    Thank you alot 🙂

  15. kevin July 14, 2011 at 2:28 pm

    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.

  16. ario August 16, 2011 at 6:17 pm

    thanks for your tuto!!!
    It’s so good

  17. Ahmad Faraz August 23, 2011 at 11:46 am

    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

  18. Sonia October 7, 2011 at 12:08 pm

    Thanks for the post. Nice code….

  19. korrupt codder October 17, 2011 at 2:03 pm

    i want to download in my assests folder what output path should be declare??

  20. Mohamed Ashraf November 11, 2011 at 10:57 am

    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
    }

  21. Sam November 18, 2011 at 8:00 pm

    Check that your emulator has some storage space assigned to it, if not it will throw an error and behave like you have described..

  22. Anoop November 24, 2011 at 9:54 am

    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

  23. Sumit January 9, 2012 at 8:16 am

    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….

  24. raj December 2, 2012 at 12:34 pm

    How do I implement a cancel download option in this program?

  25. akki February 19, 2013 at 2:16 pm

    hi could u tel me how to download a file using service if possible plzzzzzzzzzzzzzzzzz

  26. Neha Pandya May 30, 2017 at 8:59 am

    This code is very useful.but when i download xlsx file it displays as binary format can you solve this problem?

Leave a Reply