ProgressBars and AsyncTasks

I was playing around with styling a ProgressBar and needed a thread type mechanism to update it. My goal was for the ProgressBar to do its thing and then disappear from the layout once it reached 100%. Initially I used a Thread, but this left me unable to get at the UI thread. Instead I created an AsyncTask. This is a very flexible mechanism for running background processes in Android.

In order to use AsyncTask in Android you extend the class like this:

class MyAsyncTask extends AsyncTask 

Those three types (Void, Integer and Void in my case) represent the parameters sent into the task, the progress of the task (which can be published periodically if you like) and the results of the task. The parameters and the progress are Varargs, although I only used the first slot of each in my simple example.

My doInBackground looks like this:

@Override
protected Void doInBackground(Void... params) {
while (mProgressStatus < 100) {
publishProgress(doWork());
}
return null;
}

I am ignoring the params in this case. doWork() is just a private method on the containing class which loops to a big number. I am passing its result (an incrementing local variable) to publishProgress - more on that below. I don't return any results here.

This bit is how I got to update the UI thread:

@Override
protected void onPostExecute(Void res) {
super.onPostExecute(res);
mProgress.setVisibility(View.GONE);
}
This method as its name suggests runs after the task is completed, but is executed on the UI thread, so you are able to get at View objects to update them if you like. In my case I am just removing the ProgressBar as it has done its job.

Now back to that call to publishProgress. This results in this method being called:

@Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}


To kick this all off I just did this from the onCreate (or wherever you want the ProgressBar to start doing its thing):
new MyAsyncTask().execute(null, null, null);

All in all a pretty straightforward technique with a lot of potential uses in Android.



Comments

Popular posts from this blog

Building a choropleth map for Irish agricultural data

Early Stopping with Keras

AutoCompleteTextView backed with data from SQLite in Android