MainThread and Background Thread and AsyncTask in Android

MainThread vs. Background Thread
In Android there is a concept of the Main Thread or UI Thread. If you’re not sure what a thread is in computer science, check out this wikipedia article. The main thread is responsible for keeping the UI running smoothly and responding to user input. It can only execute one task at a time. If you start a process on the Main Thread which is very long, such as a complex calculation or loading process, this process will try to complete. While it is completing, though, your UI and responsiveness to user input will hang.

Therefore, whenever you need to start a longer process you should consider using another “Background” thread, which doesn’t “block” the Main Thread. An easy (but by no means perfect) way to do this is to create a subclass of AsyncTask.

AsyncTask
AsyncTask is an easy to use Android class that allows you to do a task on a background thread and thus not disrupt the Main Thread. To use AsyncTask you should subclass it as we’ve done with FetchWeatherTask. There are four important methods to override:

onPreExecute – This method is run on the UI before the task starts and is responsible for any setup that needs to be done.

doInBackground – This is the code for the actual task you want done off the main thread. It will be run on a background thread and not disrupt the UI.

onProgressUpdate – This is a method that is run on the UI thread and is meant for showing the progress of a task, such as animating a loading bar.

onPostExecute – This is a method that is run on the UI after the task is finished.

Note that when you start an AsyncTask, it is tied to the activity you start it in. When the activity is destroyed (which happens whenever the phone is rotated), the AsyncTask you started will refer to the destroyed activity and not the newly created activity. This is one of the reasons why using AsyncTask for a longer running task is dangerous.

Anroid AsyncTask Example

Reference:
The above note is taken directly from the tutorial Developing Android Apps by Google on Udacity.
https://www.udacity.com/course/viewer#!/c-ud853/l-1469948762/m-3637468791

Search within Codexpedia

Custom Search

Search the entire web

Custom Search