init进程
init进程是Android系统中用户空间的第一个进程,作为第一个进程,它被赋予了很多极其重要的工作职责,比如创建zygote(孵化器)和属性服务等。init进程是由多个源文件共同组成的,这些文件位于源码目录system/core/init。
Zygote进程
在Android系统中,DVM(Dalvik虚拟机)、应用程序进程以及运行系统的关键服务的SystemServer进程都是由Zygote进程来创建的,我们也将它称为孵化器。它通过fork(复制进程)的形式来创建应用程序进程和SystemServer进程,由于Zygote进程在启动时会创建DVM,因此通过fork而创建的应用程序进程和SystemServer进程可以在内部获取一个DVM的实例拷贝。
Zygote进程共做了如下几件事:
1.创建AppRuntime并调用其start方法,启动Zygote进程。
2.创建DVM并为DVM注册JNI.
3.通过JNI调用ZygoteInit的main函数进入Zygote的Java框架层。
4.通过registerZygoteSocket函数创建服务端Socket,并通过runSelectLoop函数等待ActivityManagerService的请求来创建新的应用程序进程。
5.启动SystemServer进程。
下面我们主要看一下SystemServer启动服务相关的源码分析
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
如上是SystemServer的入口,可以看到调用了其run方法。
private void run() {
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
......
Looper.prepareMainLooper();
......
// Initialize native services.
System.loadLibrary("android_servers");
......
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
......
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
......
Looper.loop();
......
}
以上SystemServer的run方法的源码,印证了我们前面思维导图中列举的SystemServer的几大功能点:
- Binder线程池相关
- SystemServiceManager相关
- 启动服务相关
下面重点看一下SystemServer启动服务相关分析:
上述这些服务会被注册到ServiceManager中,通过Binder IPC,提供服务。
学习资料:http://liuwangshu.cn/tags/Android%E7%B3%BB%E7%BB%9F%E5%90%AF%E5%8A%A8/