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.



1 comment: