从启动说起
Android系统加载时,首先启动init进程,该进程会启动Zygote进程。Zygote进程执行/system/bin/app_process程序。app_process程序在执行中,通过AppRuntime::start()函数来创建虚拟机实例,并注册JNI方法。
int main(int argc, const char* const argv[]) { ... if (zygote) { runtime.start("com.android.internal.os.ZygoteInit", startSystemServer ? "start-system-server" : ""); } ... }
/* * Start the Android runtime. This involves starting the virtual machine * and calling the "static void main(String[] args)" method in the class * named by "className". * * Passes the main function two arguments, the class name and the specified * options string. */ void AndroidRuntime::start(const char* className, const char* options) { ... }
public static void main(String argv[]) { ... try { if (argv[1].equals("start-system-server")) { startSystemServer(); ... }
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException { … int pid; try { … /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { handleSystemServerProcess(parsedArgs); } return true; }
接下来,调用RuntimeInit.zygoteInit()方法完成其它的初始化工作。其中,将会调用SystemServer.main()方法进入SystemServer本身的初始化。main()方法经过一系列的步骤之后,调用本地方法init1()来启动SurfaceFlinger和SensorService这样的关键服务。之后init1()从本地回调Java层的SystemServer.init2()方法来启动Java层的各项服务:
public static final void init2() { Slog.i(TAG, "Entered the Android system server!"); Thread thr = new ServerThread(); thr.setName("android.server.ServerThread"); thr.start(); }
SystemThread是一个线程子类,在这个线程的执行中,将建立一个消息循环,接着启动系统的各个服务,并注册到ServiceManager中。
终于可以进入主题了。在这里,就包括AccountManagerService的创建与注册:
class ServerThread extends Thread { private static final String TAG = "SystemServer"; … @Override public void run() { ... Looper.prepare(); ... AccountManagerService accountManager = null; ... // Critical services... try { ... // The AccountManager must come before the ContentService try { Slog.i(TAG, "Account Manager"); accountManager = new AccountManagerService(context); ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager); } catch (Throwable e) { Slog.e(TAG, "Failure starting Account Manager", e); } ... } ... }