How to:‎ > ‎

Create A Custom Progress Bar Using AsyncTask

Overview:
If you have an Activity which needs to download content or perform operations that can be done in the background AsyncTask allows you to maintain a responsive user interface and publish progress for those operations to the user.

Create your inner class which extends AsyncTask<Params, Progress, Result>:
AsyncTask has three generic types - 
Params: the type of the parameters sent to the task upon execution
Progress: the type of progress units published during the background computation
Result: the type of the result of the background computation

The primary methods to implement -
public Result doInBackground(Params...param)
public void onProgressUpdate(Progress...progress)
public void onPostExecute(Result result)

doInBackground: the entry point to the Thread and it is where the background computation will be going on.

onProgressUpdate: called whenever publishProgress(Progress...progress) is called from within doInBackground(), this method is executed by the Activity thread and can access all member variables.

onPostExecute: called as soon as doInBackground() returns, with the value that was returned as its parameter.  This method is executed by the Activity thread and can access all member variables.

Example:
Say you want to download and display an image, you want a load bar while the image is being downloaded and then have it displayed as soon as it is finished.  Your code might look something like this:

    private class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {
//This class definition states that DownloadImageTask will take String parameters, publish Integer progress updates, and return a Bitmap
        protected Bitmap doInBackground(String...paths) {
            URL url = new URL(paths[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//The String parameter represents the URL of the file you are downloading, you could also just use URL for the Params type
            int length = connection.getContentLength();
            InputStream is = (InputStream) url.getContent();
            byte[] imageData = new byte[length];
            int buffersize = (int) Math.ceil(length / (double) SIZE);
            int downloaded = 0;
            for (int i = 1; i < SIZE; i++) {
//This for loop splits the downloading into SIZE increments, so publishProgress() will be called SIZE times at equal intervals in the download
                int read = is.read(imageData, downloaded, buffersize);
                downloaded += read;
                publishProgress(i);
//publishProgress() is called with the for loop counter, so (i / SIZE) represents the percentage completed
            }
            is.read(imageData, downloaded, length - downloaded);
            publishProgress(SIZE);
            return BitmapFactory.decodeByteArray(imageData, 0, length);
//When finished, return the resulting Bitmap, this will cause the Activity to call onPostExecute()
        }

        protected void onProgressUpdate(Integer...progress) {
//This is a very simple load bar, with SIZE = 10, on step 5 this would display:  [=====     ]
            String text = "Downloading\n[";
            for (int i = 0; i < progress[0]; i++) {
                text += '=';
            }
            for (int i = SIZE; i > progress[0]; i--) {
                text += "  ";
            }
            text += "]";
            m_vwLoad.setText(text);
//You can make a much prettier load bar using a SurfaceView and drawing progress or creating drawable resources and using an ImageView 
        }

        protected void onPostExecute(Bitmap result) {
            m_vwLoad.setVisibility(View.GONE);
            m_vwImage.setVisibility(View.VISIBLE);
            m_vwImage.setImageBitmap(result);
//Hide the load bar, show the image, and set the image display to the resulting Bitmap
        }
    }

This background download would be initiated by calling the following line of code from within the Activity where PATH is the URL path of the image.
    new DownloadImageTask().execute(PATH);

There are some additional methods not used in this example, they are described below:
public void onCancelled()
public void onPreExecute()

onCancelled: called when cancel(boolean) is called from within doInBackground(), this method is executed by the UI thread.

onPreExecute: called on the UI thread before doInBackground().


For additional information on AsyncTask check out:
and
Comments