Android系统的启动流程

Android系统有哪些进程

在Linux系统启动时,会读取init.rc,里面配置了一些需要启动的进程。注意:SystemServer进程不在init.rc里,因为SystemServer进程是由zygote启动的。
如下所示:

service zygote /system/bin/app_process ...
service servicemanager /system/bin/servicemanager ...
service sufaceflinger /system/bin/suerfaceflinger ...
service media /system/bin/mediaserver ...
...

Zygote是怎么启动的?

  • init进程fork出zygote进程
  • 启动虚拟机,注册JNI函数
  • 预加载系统资源(常用类、主题资源、JNI函数、共享库等)
  • 启动SystemServer
private static boolean startSystemServer(...){
    String args[] = {
        ...
         "com.android.server.SystemServer",
    };
    int pid = Zygote.forkSystemServer(...);
    if(pid==0){
         handleSystemServerProcess(parsedArgs);
    }
    return true;
}
......
void handleSystemServerProcess(Arguments parsedArgs){
    RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,parsedArgs.remainingArgs,...);
}
......
void zygoteInit(String[] argv,...){
        commonInit();  //常规初始化
        nativeZygoteInit(); //调用native的onZygoteInit,启动binder。
        applicationInit(argv,...);  //调用Java类(SystemServer)的main函数
}
......
virtual void onZygoteInit(){
     sp proc = ProcessState::self();
    proc->startThreadPool();
}
......
void applicationInit(...){
    invokeStaticMain(args,...);//调用Java类(SystemServer)的main函数
}
......

SystemServer.java

public static void main(String[] args){
     new SystemServer().run();
}
......
private void run(){
    Looper.prepareMainLooper(); //创建主线程looper

    System.loadLibrary("android_servers");  //加载native层的SystemServer代码
    createSystemContext();  //创建系统上下文

    startBootstrapServices(); //启动引导服务
    startCoreServices(); //启动核心服务
    startOtherServices(); //启动其他服务
    Looper.loop();  //开启循环
}
  • 进入Socket Loop
boolean runOnce(){
    String[] args = readArgumentList();
    int pid = Zygote.forkAndSpecialize();
    if(pid==0){
        //in child process
        handleChildProc(args,...);
        //should never get here, the child is expected to either throw ZygoteInit.MethodAndArgsCaller or exec().
        return true;
    }else{
        return handleParentProc(pid,...);
    }
}

系统服务是怎么发布,让应用程序可见?

void publisBinderService(String name,IBinder service){
    publishBinderService(name,service,false);
}

void publishBinderService(String name,IBinder service,...){
    ServiceManager.addService(name,service,allowIsolated);
}

系统服务运行在什么线程?

工作线程:AMS、PMS、PackageManagerService
还有一些运行在公用的线程中,如在DisplayThread,FgThread,IoThread,UiThread线程中运行。
binder线程:应用接收到binder调用后,启动线程。

系统服务的互相依赖是如何解决的?

  • 分批启动
    AMS, PMS, PKMS
  • 分阶段启动
    阶段1,阶段2,阶段3,……

桌面的启动

public void systemReady(final Runnable goingCallback){
    ……
    //启动桌面程序的Launcher类
    startHomeActivityLocked(mCurrentUserId,"systemReady");
    ……
}
//Launcher(Activity)的onCreate方法中会创建一个LoaderTask
mLoaderTask = new LoaderTask(mApp.getContext(),loadFlags);
//在LoaderTask中会去向Package ManagerSevice查询已安装应用,然后将应用图标显示在桌面,当用户点击图标时,Launcher就会启动应用程序。
mPm.queryIntentActivitiesAsUser();


你可能感兴趣的:(Android系统的启动流程)