-ZygoteforkZygoteforkSystemServer进程如下:配置#System_server参数,uidgid进程显示名等,然后调用nativefork,调用handleSystemServerProcessZygoteInit.javaprivatestaticRunnableforkSystemServer(StringabiList,StringsocketName,ZygoteServerzygoteServer){/*Hardcodedcommandlinetostartthesystemserver/Stringargs[]={"--setuid=1000","--setgid=1000","--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010","--capabilities="+capabilities+","+capabilities,"--nice-name=system_server","--runtime-args","--target-sdk-version="+VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,"com.android.server.SystemServer",};try{/请求fork系统服务器进程/pid=Zygote.forkSystemServer(parsedArgs.uid,parsedArgs.gid,parsedArgs.gids,parsedArgs.runtimeFlags,null,parsedArgs.permittedCapabilities,parsedArgs.effectiveCapabilities);}catch(IllegalArgumentExceptionex){thrownewRuntimeException(ex);}/对于子进程*/if(pid==0){if(hasSecondZygote(abiList)){waitForSecondaryZygote(socketName);}zygoteServer.closeServerSocket();returnhandleSystemServerProcess(parsedArgs);}returnnull;}1.2System_service进程启动,准备加载的ClassLoaderZygoteInit.javaprivatestaticRunnablehandleSystemServerProcess(ZygoteConnection.ArgumentsparsedArgs){//将umask设置为0077,这样新文件和目录将默认为仅所有者permissions.if(parsedArgs.invokeWith!=null){}else{ClassLoadercl=null;if(systemServerClasspath!=null){cl=createPathClassLoader(systemServerClasspath,parsedArgs.targetSdkVersion);Thread.currentThread().setContext类加载器(cl);}/**将剩余的参数传递给SystemServer。*/returnZygoteInit.zygoteInit(parsedArgs.targetSdkVersion,parsedArgs.remainingArgs,cl);}/*永远不要到达这里*/}1.3RuntimeInit初始化,进一步环境初始化ZygoteInit.javapublicstaticfinalRunnablezygoteInit(inttargetSdkVersion,String[]argv,ClassLoaderclassLoader){RuntimeInit.commonInit();ZygoteInit.nativeZygoteInit();returnRuntimeInit.applicationInit(targetSdkVersion;class}Loaderv)1.4通过findStaticMain方法反射调用System_Server的main方法启动类的staticmainreturnfindStaticClass(args.startstartArgs,classLoader);}两个SystemServer进程2.1SystemServer启动,然后运行run方法。SystemServer.javapublicstaticvoidmain(String[]args){newSystemServer().run();}publicSystemServer(){//检查工厂测试模式.mFactoryTestMode=FactoryTest.getMode();//记住是运行时重启(当sys.boot_completed已经设置时)还是重启mRuntimeRestart="1".equals(SystemProperties.get("sys.boot_completed"));mRuntimeStartElapsedTime=SystemClock.elapsedRealtime();mRuntimeStartUptime=SystemClock.uptimeMillis();}2.2System_Server的run方法首先配置VM参数Binder参数,Loop.prepareMainLooper,创建系统ContextcreateSystemContext,启动系统的各种服务,包括AMS。startBootstrapServices()startCoreServices()startOtherServices()Looper.Loop();privatevoidrun(){try{......//属性。http://b/11463182SystemProperties.set("persist.sys.dalvik.vm.lib.2",VMRuntime.getRuntime().vmLibrary());//嗯嗯...更多内存!VMRuntime.getRuntime().clearGrowthLimit();//系统服务器必须一直运行,因此它需要//尽可能高效地使用内存。VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);......//确保对系统的绑定调用始终以前台优先级运行。BinderInternal.disableBackgroundScheduling(true);//增加system_server中的binder线程数BinderInternal.setMaxThreads(sMaxBinderThreads);//准备主循环线程(thisthread)。android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);android.os.Process.setCanSelfBackground(false);Looper.准备ainLooper();Looper.getMainLooper().setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS,SLOW_DELIVERY_THRESHOLD_MS);//初始化本地服务。System.loadLibrary("android_servers");//初始化系统上下文。createSystemContext();}finally{}//启动服务。try{traceBeginAndSlog("StartServices");启动引导服务();启动核心服务();启动其他服务();SystemServerInitThreadPool.shutdown();}catch(Throwableex){}finally{traceEnd();}StrictMode.initVmDefaults(null);//永远循环。Looper.loop();thrownewRuntimeException("Mainthreadloopunexpectedlyexited");}三AMS运行SystemServer#startBootstrapServices通过mSystemServiceManager启动ActivityManagerService启动ActivityManagerService3.1mSystemServiceManager.startServiceprivatevoidstartBootstrapServices(){//活动管理器运行show.mActivityManagerService=mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setSystemProcess();3.2启动ActivityManagerServiceActivityManagerService准备工作线程,准备Android四大组件相关的数据结构,publicActivityManagerService(ContextsystemContext)mContext=systemCotexmSystemThread=ActivityThread.currentActivityThread();mUiContext=mSystemThread.getSystemUiContext();mHandlerThread=newServiceThread(TAG,THREAD_PRIORITY_FOREGROUND,false/*allowIo*/);mHandlerThread.start();mHandler=newMainHandler(mHandlerThread.getLooper());mUiHandler=mInjector.getUiHandler(this);mFgBroadcastQueue=newBroadcastQueue(this,mHandler,"foreground",BROADCAST_FG_TIMEOUT,假);mBgBroadcastQueue=newBroadcastQueue(this,mHandle"background",BROADCAST_BG_TIMEOUT,true);mBroadcastQueues[0]=mFgBroadcastQueue;mBroadcastQueues[1]=mBgBroadcastQueue;mServices=newActiveServices(this);mProviderMap=newProviderMap(this);mStackSupervisor=createStackSupervisor();mActivityStarter=newActivityStarter(this,mStackSupervisor);mRecentTasks=newRecentTasks(this,mStackSupervisor);}3.3AMSsetSystemProcess()AMS通过setSystemProcess把System_Server进入AMS的进入管理中加载framework-res.apkpublicvoidsetSystemProcess(){try{ServiceManager.addService(Context.ACTIVITY_SERVICE,this,/*allowIsolated=/true,DUMP_FLAG_PRIORITY_CRITICAL|DUMP_FLAG_PRIORITY_NORMAL|DUMP_FLAG_PROTO);ServiceManager.addService(ProcessStats.SERVICE_NAME,mProcessStats);ServiceManager。addService("meminfo",newMemBinder(this),/allowIsolated=*/false,DUMP_FLAG_PRIORITY_HIGH);ServiceManager.addService("gfxinfo",newGraphicsBinder(this));ServiceManager.addService("dbinfo",newDbBinder(this));ServiceManager.addService("permission",newPermissionController(this));ServiceManager.addService("processinfo",newProcessInfoService(this));ApplicationInfo信息=mContext.getPackageManager().getApplicationInfo("android",STOCK_PM_FLAGS|MATCH_SYSTEM_ONLY);mSystemThread.installSystemApplicationInfo(信息,getClass().getClassLoader());同步(这个){ProcessRecordapp=newProcessRecordLock编(信息,信息.processName,假,0);app.persistent=true;app.pid=MY_PID;app.maxAdj=ProcessList.SYSTEM_ADJ;app.makeActive(mSystemThread.getApplicationThread(),mProcessStats);同步(mPidsSelfLocked){mPidsSelfLocked.put(app.pid,app);}updateLruProcessLocked(app,false,null);updateOomAdjLocked();}}catch(PackageManager.NameNotFoundExceptione){thrownewRuntimeException("Unabletofindandroidsystempackage",e);}}3.4installSystemProvidersinstallSettingProvidermActivityManagerService.installSystemProviders()instartOtherServices;3.5setWindowManagerActivityManagerService.setWindowManager(wm);3.6systemReady各种服务启动后,systemReady。在systemReady中先启动SystemUI,再启动Launcher。
