Dealing with Threads in Android

An Android application uses its Main Application Thread ( also known as the UI thread), to perform most of the callbacks in the application. Therefore, an overload in the Main thread leads to an “Application Not Responding” (ANR) error.
So, it is always safe to handle heavy processes (which could ultimately slow down the main thread and lead ANR) in a different background thread.

Although this sounds easy, it has a major limitation when using background threads. Unfortunately, you can not modify the application’s UI through a background thread. You will have to get the final result through a background thread and pass that to the main thread to do any modification in the UI.

With the introduction of “AsyncTask” after Android 1.5 it is easy to accomplish background work.

Stages of an AsyncTask

  1. doInBackground() – Inside this method, you can perform whatever task you need to perform in a background thread.
  2. onPreExecute() – This is called just before executing doInBackground() and can be used to indicate the background process is going to start. (Eg: Initialising the progress bar)
  3. onPostExecute() – This is called right after the doInBackground() has been completed and can be used to inform the completion of the task. (Eg: Dismissing the progress bar)
  4. onProgressUpdate() – This runs in the main thread after the publishProgress() is invoked inside the doInBackground(). This can be used to update the user about the continuation of the background task. (Eg: Updating the progress bar)

NOTE:

publishProgress() is a method which can be called from doInBackground() and publishes progress updates to the UI thread.

Syntax for AsyncTask

private class SampleAsyncTask extends AsyncTask<Void, Void, Void> 

There are 3 generic types used in AsyncTask

  1. Params – Parameter type to be sent to the task for execution
  2. Progress – Type of progress parameter passed when calling progressUpdate()
  3. Result – The result type from the background task

Leave a comment

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