Sunday, May 31, 2015

Concurrent Programming Model in Android...

Note : Here are my two tutorials on Android Concurrency Model. Please have a look at these:
  1. https://youtu.be/zWdVVI7kH4E
  2. https://youtu.be/1J6iqKJgvDU
When an Android application is launched, the Android system creates a thread of execution for the application. This is known as the main thread. This is also known as the UI thread because all the android widgets used for this application run in the context of this main thread. Every UI thread will have its own looper by default which in association with a Message Queue is responsible for dispatching the user interface events to the appropriate widgets. This has been depicted in the following diagram:



We need to arrange our application components so that the UI thread always remains responsive.

Hence we cannot do a long running task like connecting to a network server and downloading a big file or doing a CRUD operation on a remote database in the main UI thread. if we do it then the long running task will block the UI thread and it will freeze the UI. Moreover, if the duration of this freezing of the UI thread is more than 5 seconds, we will get an "Application Not Responding" message which is not desirable. Hence we should do the long running task in a background UI thread.

Another important fact about Android is that the UI toolkit is not thread safe. Hence we cannot manipulate the UI thread from a background worker thread.

Thus there are simply two rules in Android application model vis-a-vis concurrency framework:

1. We should not block the UI thread
2. We should not manipulate the UI thread from a background thread.

Keeping in mind all these factors, there are mainly two ways of doing concurrent programming in Android:

1. Asynctask
2. Handler, Message & Runnable

This has been depicted in the following diagram.



Here are three different applications which show how we can write a concurrent program in Android and communicate to the main thread from a background thread.

You can browse/download the source code of these apps from here:

1. https://github.com/sommukhopadhyay/AsynctaskDownloadImage

2. https://github.com/sommukhopadhyay/DownloadImageWithRunnable

3. https://github.com/sommukhopadhyay/DownloadImageWithMessageHandler

The first has used an Asynctask, the second has used the function Activity.runOnUIThread and the third has used Handler & Message to achieve the same purpose.

Hopefully this will help you to understand the concurrent framework of Android.