Monday, November 14, 2011

Android UI Thread

In this post I will try to explain Android UI thread basic.

INTRODUCTION :
As explained in last post, When an application is launched, A new process created to host it with its own Darvik VM instance, application also gets single thread knows as UI/Main thread,(thread responsible for UI display or update)


CONCEPT :
In almost every OS, for UI updating, there is a UI thread, which runs an infinite loop and checks a queue to see if there are any pending UI events.
In case of Android, above concept is implemented with help of :
1. Looper 3. messages
4. Handler
The looper loops over a MessageQueue which contains the messages to be dispatched. The actual task of managing the queue is done by a Handler which is responsible for handling (adding, removing, dispatching) messages in the message queue.

Looper and handler :
1. Looper can be associated only with one thread and association cannot be changed.
2. Mulitple handlers can be associated with a message queue.
3. Blocking operation on the UI thread leads to Application not responding(ANR) dialog.




Android Rule for updating UI :

1. Do not block the UI thread.
2. Do not access the Android UI toolkit from outside the UI thread.


For example :
Consider below example for updating UI from worker thread:
Above example violates the second android Rule for updating UI.This can result in undefined and unexpected behavior.

To fix this problem, Android offers:
1. Activity.runOnUiThread(Runnable)
2. View.post(Runnable)
3. View.postDelayed(Runnable, long)

Above problem can be fixed with below solution :
Now this implementation is thread-safe: the network operation is done from a separate thread while the ImageView is manipulated from the UI thread.However, as the complexity of the operation grows, this kind of code can get complicated and difficult to maintain.

Android suggestion for handling above scenario :
1. Handler
2. AsyncTask


1. Handler :
Handler provide bridge for new threads to add messages to messages queue.

Other methods for accessing message queue :
handler.sendMessageAtFrontOfQueue()
handler.sendMessageAtTime()
handler.sendMessageDelayed()
handler.sendEmptyMessage()

Description :

Handler have handleMessage() which has msg argument, which is used for updating UI.


For sending msg to Handler, we can obtain message from Handler object and manipulate msg.obj and then send message to handler, which is handled by handleMessage() .


2. AsyncTask :
It’s a wrapper for a threaded operation, what all we did in above example.


Description:

Above line consist of 3 parameter for AsyncTask
1. Params : parameter passed to doInBackground(Integer... params)
2.Progress : parameter passed to onProgressUpdate(String... progress)
3.Result : parameter passed to onPostExecute(Long result)


doInBackground() :Code in this method is handled in a sperate thread. Note that the data type of the return value corresponds to the type third parameter in the class definition. Returned value from this method is passed to the onPostExecute() method when this thread completes.

Datatype passed corresponds to the first parameter in the class definition.

onProgressUpdate() :Report progress. datatype passed corresponds to the second parameter in the class definition. This callback can be triggered from within the body of the doInBackground() method by calling publishProgress()

onPostExecute() :This method is called when the thread has completed successfully. Note that the datatype passed to this parameter matches the third parameter in the method definition.

The AsyncTask class also provides helpful callback methods likeonCancelled() which handles the cancellation of the thread and onPreExecute() which is called just before the thread calls doInBackground().





Thursday, November 10, 2011

Android Zygote and Processes




Recently i was working on improving boot time and application launch time in android. Interestingly, what hold my attention was a neat and simple design of Android framework for maintaining, running processes and applications.

Android Start-up Sequences:
1. Boot-loader load kernel and start init process. give a look to init.rc structure here.
2. Init process spawns multiple demons e.g. android debug etc.
3. Init also start Interesting process Zygote, as name implies(very 1st step for every android process )
4. Zygote then fork to start SYSTEM PROCESS(core platform services).i.e. power manager, activity manager etc.
5. Once all system process are up, Home app display home screen and android is ready to launch very 1st app.


Zygote consist of :
1. Instance of Dalvik virtual machine with preloaded classes needed by android application app.
2. Registered socket for future request to spawn off new Dalvik virtual machine.
3. Once new request come Zygote forks itself and create new process with pre-loaded DVM.


Android application launch:
There are three distinct phases of process launch :
1. Process Creation.
2. Binding Application
3. Launching Activity, Service etc.

Process Creation -
ActivityManagerService creates a new process by invoking startProcessLocked() method which sends arguments to Zygote process over the socket connection. Zygote forks itself and calls ZygoteInit.main() which then instantiates ActivityThread object and returns pid of newly created process.

Binding Application -
Now need to load Application specific classes in memory, for this we need to bind application that i can be done by calling bindApplication on the thread object. This method sends BIND_APPLICATION message to the message queue, message trigger specific action - handleBindApplication(). This method invokes makeApplication() method which loads app specific classes into memory.

Activity Launch -
For starting activity, ActivityManagerService call realStartActivity() method which calls sheduleLaunchActivity() on the application thread object. This method sends LAUNCH_ACTIVITY message to the message queue. The message is handled by handleLaunchActivity() methodand call onCreate().

Important Note about Android application -
1. Every Android application run in a separate process, has its own Dalvik VM and is assigned a unique user ID.
2. Android Application have a multiple entry point, which can be defined in androidmanifest.xml.