Displaying notifications and progress bar from an instance of AsyncTask

The AsyncTask class is used to perform background tasks and it might be useful to show notifications and progress bars to alert the user.
In this post I write an example where I create two AsyncTask instances showing a startup notification, a progress bar and a notification of completed task

    1. the MainActivity class, the main activity

      when you click the button inside the layout you create two AsyncTask instances, if the API version is less than 11 (HONEYCOMB) the AsyncTask instances are launched with the execute() method otherwise with the executeOnExecutor() method available from API version 11.
      It is better to launch the AsyncTask using the executeOnExecutor() method because in this way they are executed at the same time and it is more obvious what I want to show.
    2. the NotificationTask class extending AsyncTask

there are three overidden methods:

      • onPreExecute(): here I initialize the notifications, especially I set the id passed to the constructor (line 163), then the two AsynTask instances have id equal to 1 and 2
      • doInBackground(Integer… params): I wait 3 seconds and after I display the progress bar, in the first AsyncTask instance the time is 10 seconds, in the second one it is 5 seconds, these values are set as argument in the execute() or executeOnExecutor() methods.
      • onPostExecute(Void result): the notification “completed” opening the ResultActivity
  1. the ResultActivity class displayed when the user click on the notification “completed”
  2. AndroidManifest.xml
  3. the layouts, very easy
    • res/layout/activity_main.xml
    • res/layout/activity_result.xml

The following are the screen shots of the app, note that the notifications are split according to the id.
main started downloading completed result

Here you can download the source code of the app.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.