Android UI Main Thread
Android handles input events/tasks with a single User Interface (UI) thread and the thread is called Main thread. Main thread cannot handle concurrent operations as it handles only one event/operation at a time.
Concurrent Processing in Android
If input events or tasks are not handled concurrently, whole code of an Android application runs in the main thread and each line of code is executed one after each other.
Assume if you perform a long lasting operation, for example accessing resource (like MP3, JSON, Image) from the Internet, the application goes hung state until the corresponding operation is finished.
To bring good user experience in Android applications, all potentially slow running operations or tasks in an Android application should be made to run asynchronously.
Here are some examples for slow running tasks
Accessing resources (like MP3, JSON, Image) from Internet
Complex logic that takes quite long time
AsyncTask in Android
What is AsyncTask?
AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.
When to use AsyncTask?
Assume you have created a simple Android application which downloads MP3 file from Internet on launching the application.
The below state diagram shows the series of operations that will take place when you launch the application you created:
As the response (MP3 file) from server is awaited, the application has become unresponsive since the Main thread is still waiting for download operation to complete. To overcome this we can create new thread and implement run method to perform this network call as similar as we usually do in normal Java applications, so that UI remains responsive.
But handling it with separate thread may create some additional issues when we try to update UI based on the result of the operation performed since Android UI toolkit is not thread safe.
Android took all these issues in consideration and created a dedicated class called ‘AsyncTask’ to handle the tasks/operations that need to be performed at the background asynchronously.