intmain(intargc,char**argv){.../*清除 umask*/umask(0);/*创建目录,挂载文件系统*/mkdir("/dev",0755);mkdir("/proc",0755);mkdir("/sys",0755);mount("tmpfs","/dev","tmpfs",MS_NOSUID,"mode=0755");mkdir("/dev/pts",0755);mkdir("/dev/socket",0755);mount("devpts","/dev/pts","devpts",0,NULL);mount("proc","/proc","proc",0,NULL);mount("sysfs","/sys","sysfs",0,NULL);/*猜猜这句是干什么?很有意思 哈哈!*/close(open("/dev/.booting",O_WRONLY|O_CREAT,0000));/*打开 /dev/null 并将 0,1,2 重定向到 /dev/null*/open_devnull_stdio();klog_init();/*初始化 property 详见[android properties][101]*/property_init();get_hardware_name(hardware,&revision);process_kernel_cmdline();/*selinux 相关*/unionselinux_callbackcb;cb.func_log=klog_write;selinux_set_callback(SELINUX_CB_LOG,cb);cb.func_audit=audit_callback;selinux_set_callback(SELINUX_CB_AUDIT,cb);selinux_initialize();restorecon("/dev");restorecon("/dev/socket");restorecon("/dev/__properties__");restorecon_recursive("/sys");/*load 默认的properties*/if(!is_charger)property_load_boot_defaults();/*init 的主要工作之一:解析 init.rc */INFO("reading config file\n");init_parse_config_file("/init.rc");/*action_for_each_trigger 和 queue_builtin_action 将 action/command 都是加入到 command 队列里面,等待合适的时机执行*/action_for_each_trigger("early-init",action_add_queue_tail);queue_builtin_action(wait_for_coldboot_done_action,"wait_for_coldboot_done");queue_builtin_action(mix_hwrng_into_linux_rng_action,"mix_hwrng_into_linux_rng");queue_builtin_action(keychord_init_action,"keychord_init");queue_builtin_action(console_init_action,"console_init");/* execute all the boot actions to get us started */action_for_each_trigger("init",action_add_queue_tail);if(!is_charger){action_for_each_trigger("early-fs",action_add_queue_tail);action_for_each_trigger("fs",action_add_queue_tail);action_for_each_trigger("post-fs",action_add_queue_tail);action_for_each_trigger("post-fs-data",action_add_queue_tail);}queue_builtin_action(mix_hwrng_into_linux_rng_action,"mix_hwrng_into_linux_rng");queue_builtin_action(property_service_init_action,"property_service_init");queue_builtin_action(signal_init_action,"signal_init");queue_builtin_action(check_startup_action,"check_startup");if(is_charger){action_for_each_trigger("charger",action_add_queue_tail);}else{action_for_each_trigger("early-boot",action_add_queue_tail);action_for_each_trigger("boot",action_add_queue_tail);}/* run all property triggers based on current state of the properties */queue_builtin_action(queue_property_triggers_action,"queue_property_triggers");#if BOOTCHARTqueue_builtin_action(bootchart_init_action,"bootchart_init");#endif/*解析完 init.rc 之后到此的这一段,好像都是在想队列里面添加 action/command*//*什么时候来执行呢?下面!*//*init 最后进入了一个无限循环,不会主动退出!*/for(;;){intnr,i,timeout=-1;/*执行command 队列里面的一条命令!*/execute_one_command();restart_processes();/*添加property fd (socket) 到 ufds */if(!property_set_fd_init&&get_property_set_fd()>0){ufds[fd_count].fd=get_property_set_fd();ufds[fd_count].events=POLLIN;ufds[fd_count].revents=0;fd_count++;property_set_fd_init=1;}/*添加 signal fd 到 ufds*/if(!signal_fd_init&&get_signal_fd()>0){ufds[fd_count].fd=get_signal_fd();ufds[fd_count].events=POLLIN;ufds[fd_count].revents=0;fd_count++;signal_fd_init=1;}/*添加 keychord ?fd 到 ufds*/if(!keychord_fd_init&&get_keychord_fd()>0){ufds[fd_count].fd=get_keychord_fd();ufds[fd_count].events=POLLIN;ufds[fd_count].revents=0;fd_count++;keychord_fd_init=1;}/*计算进程restart 时间*/if(process_needs_restart){timeout=(process_needs_restart-gettime())*1000;if(timeout<0)timeout=0;}if(!action_queue_empty()||cur_action)timeout=0;#if BOOTCHARTif(bootchart_count>0){if(timeout<0||timeout>BOOTCHART_POLLING_MS)timeout=BOOTCHART_POLLING_MS;if(bootchart_step()<0||--bootchart_count==0){bootchart_finish();bootchart_count=0;}}#endif/*poll出 ufds 的事件,等待 timeout 时间*/nr=poll(ufds,fd_count,timeout);if(nr<=0)continue;/*处理 ufds 事件!(property set , signal,keychord?)*/for(i=0;i<fd_count;i++){if(ufds[i].revents==POLLIN){if(ufds[i].fd==get_property_set_fd())handle_property_set_fd();elseif(ufds[i].fd==get_keychord_fd())handle_keychord();elseif(ufds[i].fd==get_signal_fd())handle_signal();}}}}
代码看下来,可以看出来,init 的主要工作就是:
解析 init.rc 文件并执行相应的 action/commands.
作为一个 Daemon 进程处理 property_set,keychord(key combo) 和 signal 事件。
#导入其他 rc 文件import /init.environ.rc
import /init.usb.rc
import /init.${ro.hardware}.rc #这里保留了导入特定平台相关 rc 的接口,这里可能导入很多东西!import /init.trace.rc
#early-init 要处理的事情on early-init
# Set init and its forked children's oom_adj. write /proc/1/oom_adj -16
# Set the security context for the init process.# This should occur before anything else (e.g. ueventd) is started. setcon u:r:init:s0
start ueventd
# create mountpoints mkdir /mnt 0775 root system
#init 要处理的事情on init
sysclktz 0
loglevel 3
# Backward compatibility symlink /system/etc /etc
symlink /sys/kernel/debug /d
# Right now vendor lives on the same filesystem as system,# but someday that may change. symlink /system/vendor /vendor
#...省略部分代码on post-fs
# once everything is setup, no need to modify / mount rootfs rootfs / ro remount
# mount shared so changes propagate into child namespaces mount rootfs rootfs / shared rec
mount tmpfs tmpfs /mnt/secure private rec
#...省略部分代码on post-fs-data
# We chown/chmod /data again so because mount is run as root + defaults chown system system /data
chmod 0771 /data
# We restorecon /data in case the userdata partition has been reset. restorecon /data
#...省略部分代码on boot
# basic network init ifup lo
hostname localhost
domainname localdomain
#...省略部分代码#这两句重要!! class_start core
class_start main
on nonencrypted
class_start late_start
on charger
class_start charger
on property:vold.decrypt=trigger_reset_main
class_reset main
#...省略部分代码service console /system/bin/sh
class core
console
disabled
user shell
group log
#...省略部分代码service servicemanager /system/bin/servicemanager
class core
user system
group system
critical
onrestart restart healthd
onrestart restart zygote
onrestart restart media
onrestart restart surfaceflinger
onrestart restart drm
#...省略部分代码service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
/* * 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. */voidAndroidRuntime::start(constchar*className,constchar*options){...if(startVm(&mJavaVM,&env)!=0){return;}...onVmCreated(env);...strArray=env->NewObjectArray(2,stringClass,NULL);assert(strArray!=NULL);classNameStr=env->NewStringUTF(className);assert(classNameStr!=NULL);env->SetObjectArrayElement(strArray,0,classNameStr);optionsStr=env->NewStringUTF(options);env->SetObjectArrayElement(strArray,1,optionsStr);.../* * Start VM. This thread becomes the main thread of the VM, and will * not return until the VM exits. */char*slashClassName=toSlashClassName(className);jclassstartClass=env->FindClass(slashClassName);if(startClass==NULL){ALOGE("JavaVM unable to locate class '%s'\n",slashClassName);/* keep going */}else{jmethodIDstartMeth=env->GetStaticMethodID(startClass,"main","([Ljava/lang/String;)V");if(startMeth==NULL){ALOGE("JavaVM unable to find main() in '%s'\n",className);/* keep going */}else{env->CallStaticVoidMethod(startClass,startMeth,strArray);}}
调用 start 的时候传递了两个参数 com.android.internal.os.ZygoteInit , start-system-server,对应 start 的两个形参 className 和 options。在 start 里面,可以看到,先是 启动了 VM , 然后将两个参数放到 VM 的 env 里面,在然后,找到 com.android.internal.os.ZygoteInit 并调用其 main 方法 !
/** * Prepare the arguments and fork for the system server process. */privatestaticbooleanstartSystemServer()throwsMethodAndArgsCaller,RuntimeException{.../* Hardcoded command line to start the system server */Stringargs[]={"--setuid=1000","--setgid=1000","--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007","--capabilities="+capabilities+","+capabilities,"--runtime-init","--nice-name=system_server","com.android.server.SystemServer",};.../* Request to fork the system server process */pid=Zygote.forkSystemServer(parsedArgs.uid,parsedArgs.gid,parsedArgs.gids,parsedArgs.debugFlags,null,parsedArgs.permittedCapabilities,parsedArgs.effectiveCapabilities);.../* For child process */if(pid==0){handleSystemServerProcess(parsedArgs);}returntrue;
staticvoidDalvik_dalvik_system_Zygote_forkSystemServer(constu4*args,JValue*pResult){pid_tpid;pid=forkAndSpecializeCommon(args,true);/* The zygote process checks whether the child process has died or not. */if(pid>0){intstatus;ALOGI("System server process %d has been created",pid);gDvm.systemServerPid=pid;/*如果 system server 没启动成功,zygote 会自杀!*/if(waitpid(pid,&status,WNOHANG)==pid){ALOGE("System server process %d has died. Restarting Zygote!",pid);kill(getpid(),SIGKILL);}}RETURN_INT(pid);}
这里 fork 之前,注册了 signal 处理函数 setSignalHandler, 子进程里面又取消了signal 处理函数,说明这个是为父进程 zygote 注册的,来看看里面干了些啥:
dalvik/vm/native/dalvik_system_Zygote.cpp
12345678910111213141516
staticvoidsigchldHandler(ints){.../* * If the just-crashed process is the system_server, bring down zygote * so that it is restarted by init and system server will be restarted * from there. */if(pid==gDvm.systemServerPid){ALOG(LOG_INFO,ZYGOTE_LOG_TAG,"Exit zygote because system server (%d) has terminated",(int)pid);kill(getpid(),SIGKILL);}...}
这里如果 system server 挂了, zygote 又要自杀!!
OK , 假设正常执行,继续回到 startSystemServer, 下一步, system server 和 zygote 分道扬镳了终于, system server 调用 handleSystemServerProcess, zygote 则调用 runSelectLoop(), 先看 zygote runSelectLoop:
dalvik/vm/native/dalvik_system_Zygote.cpp
12345678910111213141516171819202122
/** * Runs the zygote process's select loop. Accepts new connections as * they happen, and reads commands from connections one spawn-request's * worth at a time. * * @throws MethodAndArgsCaller in a child process when a main() should * be executed. */privatestaticvoidrunSelectLoop()throwsMethodAndArgsCaller{....while(true){...}elseif(index==0){ZygoteConnectionnewPeer=acceptCommandPeer();peers.add(newPeer);fds.add(newPeer.getFileDesciptor());}else{booleandone;done=peers.get(index).runOnce();}}}
acceptCommandPeer() 实际是在阻塞式的等待 client 来发起连接。
dalvik/vm/native/dalvik_system_Zygote.cpp
123456789101112
/** * Waits for and accepts a single command connection. Throws * RuntimeException on failure. */privatestaticZygoteConnectionacceptCommandPeer(){try{returnnewZygoteConnection(sServerSocket.accept());}catch(IOExceptionex){thrownewRuntimeException("IOException during accept()",ex);}}
/** * Finish remaining work for the newly forked system server process. */privatestaticvoidhandleSystemServerProcess(ZygoteConnection.ArgumentsparsedArgs)throwsZygoteInit.MethodAndArgsCaller{...RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,parsedArgs.remainingArgs);...}
privatestaticvoidapplicationInit(inttargetSdkVersion,String[]argv)throwsZygoteInit.MethodAndArgsCaller{...// Remaining arguments are passed to the start class's static maininvokeStaticMain(args.startClass,args.startArgs);}
终于到了 SystemServer 里面来了 :
SystemServer.java
12345678910
publicstaticvoidmain(String[]args){...System.loadLibrary("android_servers");// Initialize native services.nativeInit();// This used to be its own separate thread, but now it is// just the loop we run on the main thread.ServerThreadthr=newServerThread();thr.initAndLoop();}
主要干了两件事:
nativeInit
ServerThread 启动
nativeInit 好像没干啥嘛
services/jni/com_android_server_SystemServer.cpp
12345678
staticvoidandroid_server_SystemServer_nativeInit(JNIEnv*env,jobjectclazz){charpropBuf[PROPERTY_VALUE_MAX];property_get("system_init.startsensorservice",propBuf,"1");if(strcmp(propBuf,"1")==0){// Start the sensor serviceSensorService::instantiate();}}
publicvoidinitAndLoop(){...Looper.prepareMainLooper();//为 window manager 创建一个 handler.HandlerThreadwmHandlerThread=newHandlerThread("WindowManager");wmHandlerThread.start();HandlerwmHandler=newHandler(wmHandlerThread.getLooper());wmHandler.post(newRunnable(){@Overridepublicvoidrun(){android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY);android.os.Process.setCanSelfBackground(false);}});// 启动 installd , Power Manager Activity Manager service.booleanonlyCore=false;booleanfirstBoot=false;try{installer=newInstaller();installer.ping();power=newPowerManagerService();ServiceManager.addService(Context.POWER_SERVICE,power);context=ActivityManagerService.main(factoryTest);}booleandisableStorage=SystemProperties.getBoolean("config.disable_storage",false);booleandisableMedia=SystemProperties.getBoolean("config.disable_media",false);booleandisableBluetooth=SystemProperties.getBoolean("config.disable_bluetooth",false);booleandisableTelephony=SystemProperties.getBoolean("config.disable_telephony",false);booleandisableLocation=SystemProperties.getBoolean("config.disable_location",false);booleandisableSystemUI=SystemProperties.getBoolean("config.disable_systemui",false);booleandisableNonCoreServices=SystemProperties.getBoolean("config.disable_noncore",false);booleandisableNetwork=SystemProperties.getBoolean("config.disable_network",false);//各种 service add try{display=newDisplayManagerService(context,wmHandler);ServiceManager.addService(Context.DISPLAY_SERVICE,display,true);telephonyRegistry=newTelephonyRegistry(context);ServiceManager.addService("telephony.registry",telephonyRegistry);if(android.telephony.MSimTelephonyManager.getDefault().isMultiSimEnabled()){msimTelephonyRegistry=newMSimTelephonyRegistry(context);ServiceManager.addService("telephony.msim.registry",msimTelephonyRegistry);}ServiceManager.addService("scheduling_policy",newSchedulingPolicyService());StringcryptState=SystemProperties.get("vold.decrypt");if(ENCRYPTING_STATE.equals(cryptState)){onlyCore=true;}elseif(ENCRYPTED_STATE.equals(cryptState)){onlyCore=true;}pm=PackageManagerService.main(context,installer,factoryTest!=SystemServer.FACTORY_TEST_OFF,onlyCore);ActivityManagerService.setSystemProcess();ServiceManager.addService("entropy",newEntropyMixer(context));ServiceManager.addService(Context.USER_SERVICE,UserManagerService.getInstance());mContentResolver=context.getContentResolver();accountManager=newAccountManagerService(context);ServiceManager.addService(Context.ACCOUNT_SERVICE,accountManager);contentService=ContentService.main(context,factoryTest==SystemServer.FACTORY_TEST_LOW_LEVEL);ActivityManagerService.installSystemProviders();lights=newLightsService(context);battery=newBatteryService(context,lights);ServiceManager.addService("battery",battery);vibrator=newVibratorService(context);ServiceManager.addService("vibrator",vibrator);consumerIr=newConsumerIrService(context);ServiceManager.addService(Context.CONSUMER_IR_SERVICE,consumerIr);power.init(context,lights,ActivityManagerService.self(),battery,BatteryStatsService.getService(),ActivityManagerService.self().getAppOpsService(),display);alarm=newAlarmManagerService(context);ServiceManager.addService(Context.ALARM_SERVICE,alarm);Watchdog.getInstance().init(context,battery,power,alarm,ActivityManagerService.self());Watchdog.getInstance().addThread(wmHandler,"WindowManager thread");inputManager=newInputManagerService(context,wmHandler);wm=WindowManagerService.main(context,power,display,inputManager,wmHandler,factoryTest!=SystemServer.FACTORY_TEST_LOW_LEVEL,!firstBoot,onlyCore);ServiceManager.addService(Context.WINDOW_SERVICE,wm);ServiceManager.addService(Context.INPUT_SERVICE,inputManager);inputManager.setWindowManagerCallbacks(wm.getInputMonitor());inputManager.start();display.setWindowManager(wm);display.setInputManager(inputManager);imm=newInputMethodManagerService(context,wm);ServiceManager.addService(Context.INPUT_METHOD_SERVICE,imm);ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,newAccessibilityManagerService(context));wm.displayReady();pm.performBootDexOpt();mountService=newMountService(context);ServiceManager.addService("mount",mountService);if(!disableNonCoreServices){lockSettings=newLockSettingsService(context);ServiceManager.addService("lock_settings",lockSettings);devicePolicy=newDevicePolicyManagerService(context);ServiceManager.addService(Context.DEVICE_POLICY_SERVICE,devicePolicy);}if(!disableSystemUI){statusBar=newStatusBarManagerService(context,wm);ServiceManager.addService(Context.STATUS_BAR_SERVICE,statusBar);}if(!disableNonCoreServices){ServiceManager.addService(Context.CLIPBOARD_SERVICE,newClipboardService(context));}if(!disableNetwork){networkManagement=NetworkManagementService.create(context);ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE,networkManagement);}if(!disableNonCoreServices){tsms=newTextServicesManagerService(context);ServiceManager.addService(Context.TEXT_SERVICES_MANAGER_SERVICE,tsms);}if(!disableNetwork){networkStats=newNetworkStatsService(context,networkManagement,alarm);ServiceManager.addService(Context.NETWORK_STATS_SERVICE,networkStats);networkPolicy=newNetworkPolicyManagerService(context,ActivityManagerService.self(),power,networkStats,networkManagement);ServiceManager.addService(Context.NETWORK_POLICY_SERVICE,networkPolicy);wifiP2p=newWifiP2pService(context);ServiceManager.addService(Context.WIFI_P2P_SERVICE,wifiP2p);wifi=newWifiService(context);ServiceManager.addService(Context.WIFI_SERVICE,wifi);serviceDiscovery=NsdService.create(context);ServiceManager.addService(Context.NSD_SERVICE,serviceDiscovery);}if(!disableNonCoreServices){ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,newUpdateLockService(context));}/* * MountService has a few dependencies: Notification Manager and * AppWidget Provider. Make sure MountService is completely started * first before continuing. */if(mountService!=null&&!onlyCore){mountService.waitForAsecScan();}try{if(accountManager!=null)accountManager.systemReady();}try{if(contentService!=null)contentService.systemReady();}try{notification=newNotificationManagerService(context,statusBar,lights);ServiceManager.addService(Context.NOTIFICATION_SERVICE,notification);networkPolicy.bindNotificationManager(notification);}try{ServiceManager.addService(DeviceStorageMonitorService.SERVICE,newDeviceStorageMonitorService(context));}if(!disableLocation){location=newLocationManagerService(context);ServiceManager.addService(Context.LOCATION_SERVICE,location);countryDetector=newCountryDetectorService(context);ServiceManager.addService(Context.COUNTRY_DETECTOR,countryDetector);}if(!disableNonCoreServices){try{Slog.i(TAG,"Search Service");ServiceManager.addService(Context.SEARCH_SERVICE,newSearchManagerService(context));}}try{ServiceManager.addService(Context.DROPBOX_SERVICE,newDropBoxManagerService(context,newFile("/data/system/dropbox")));}if(!disableNonCoreServices&&context.getResources().getBoolean(R.bool.config_enableWallpaperService)){try{if(!headless){wallpaper=newWallpaperManagerService(context);ServiceManager.addService(Context.WALLPAPER_SERVICE,wallpaper);}}}if(!disableMedia&&!"0".equals(SystemProperties.get("system_init.startaudioservice"))){try{ServiceManager.addService(Context.AUDIO_SERVICE,newAudioService(context));}}if(!disableNonCoreServices){try{// Listen for dock station changesdock=newDockObserver(context);}}if(!disableMedia){try{// Listen for wired headset changesinputManager.setWiredAccessoryCallbacks(newWiredAccessoryManager(context,inputManager));}catch(Throwablee){reportWtf("starting WiredAccessoryManager",e);}}if(!disableNonCoreServices){try{// Manage USB host and device supportusb=newUsbService(context);ServiceManager.addService(Context.USB_SERVICE,usb);}try{// Serial port supportserial=newSerialService(context);ServiceManager.addService(Context.SERIAL_SERVICE,serial);}}try{twilight=newTwilightService(context);}try{// Listen for UI mode changesuiMode=newUiModeManagerService(context,twilight);}if(!disableNonCoreServices){try{ServiceManager.addService(Context.BACKUP_SERVICE,newBackupManagerService(context));}try{appWidget=newAppWidgetService(context);ServiceManager.addService(Context.APPWIDGET_SERVICE,appWidget);}try{recognition=newRecognitionManagerService(context);}}try{ServiceManager.addService("diskstats",newDiskStatsService(context));}try{ServiceManager.addService("samplingprofiler",newSamplingProfilerService(context));}if(!disableNetwork){try{networkTimeUpdater=newNetworkTimeUpdateService(context);}}if(!disableMedia){try{commonTimeMgmtService=newCommonTimeManagementService(context);ServiceManager.addService("commontime_management",commonTimeMgmtService);}}if(!disableNetwork){try{CertBlacklisterblacklister=newCertBlacklister(context);}}if(!disableNonCoreServices&&context.getResources().getBoolean(R.bool.config_dreamsSupported)){try{// Dreams (interactive idle-time views, a/k/a screen savers)dreamy=newDreamManagerService(context,wmHandler);ServiceManager.addService(DreamService.DREAM_SERVICE,dreamy);}}if(!disableNonCoreServices){try{atlas=newAssetAtlasService(context);ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE,atlas);}}try{newIdleMaintenanceService(context,battery);}try{printManager=newPrintManagerService(context);ServiceManager.addService(Context.PRINT_SERVICE,printManager);}if(!disableNonCoreServices){try{mediaRouter=newMediaRouterService(context);ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE,mediaRouter);}}//safe mode 相关finalbooleansafeMode=wm.detectSafeMode();if(safeMode){ActivityManagerService.self().enterSafeMode();// Post the safe mode state in the Zygote classZygote.systemInSafeMode=true;// Disable the JIT for the system_server processVMRuntime.getRuntime().disableJitCompilation();}else{// Enable the JIT for the system_server processVMRuntime.getRuntime().startJitCompilation();}//service system readyvibrator.systemReady();lockSettings.systemReady();devicePolicy.systemReady();notification.systemReady();wm.systemReady();if(safeMode){ActivityManagerService.self().showSafeModeOverlay();}power.systemReady(twilight,dreamy);pm.systemReady();display.systemReady(safeMode,onlyCore);//接下来是 ActivityManagerService 的 systemReadyActivityManagerService.self().systemReady(newRunnable(){publicvoidrun(){ActivityManagerService.self().startObservingNativeCrashes();startSystemUi(contextF);if(mountServiceF!=null)mountServiceF.systemReady();if(batteryF!=null)batteryF.systemReady();if(networkManagementF!=null)networkManagementF.systemReady();if(networkStatsF!=null)networkStatsF.systemReady();if(networkPolicyF!=null)networkPolicyF.systemReady();if(connectivityF!=null)connectivityF.systemReady();if(dockF!=null)dockF.systemReady();if(usbF!=null)usbF.systemReady();if(twilightF!=null)twilightF.systemReady();if(uiModeF!=null)uiModeF.systemReady();if(recognitionF!=null)recognitionF.systemReady();Watchdog.getInstance().start();// It is now okay to let the various system services start their// third party code...if(appWidgetF!=null)appWidgetF.systemRunning(safeMode);if(wallpaperF!=null)wallpaperF.systemRunning();if(immF!=null)immF.systemRunning(statusBarF);if(locationF!=null)locationF.systemRunning();if(countryDetectorF!=null)countryDetectorF.systemRunning();if(networkTimeUpdaterF!=null)networkTimeUpdaterF.systemRunning();if(commonTimeMgmtServiceF!=null)commonTimeMgmtServiceF.systemRunning();textServiceManagerServiceF.systemRunning();if(dreamyF!=null)dreamyF.systemRunning();if(atlasF!=null)atlasF.systemRunning();if(inputManagerF!=null)inputManagerF.systemRunning();if(telephonyRegistryF!=null)telephonyRegistryF.systemRunning();if(msimTelephonyRegistryF!=null)msimTelephonyRegistryF.systemRunning();if(printManagerF!=null)printManagerF.systemRuning();if(mediaRouterF!=null)mediaRouterF.systemRunning();//进入消息循环Looper.loop();}
system server 启动了,来看下 Launcher 是怎么启动的。system server 的最后一段调用了 ActivityManagerService 的 systemReady() 回调。
finalbooleanresumeTopActivityLocked(ActivityRecordprev){returnresumeTopActivityLocked(prev,null);}finalbooleanresumeTopActivityLocked(ActivityRecordprev,Bundleoptions){if(ActivityManagerService.DEBUG_LOCKSCREEN)mService.logLockScreen("");...if(next==null){// There are no more activities! Let's just start up the// Launcher...ActivityOptions.abort(options);if(DEBUG_STATES)Slog.d(TAG,"resumeTopActivityLocked: No more activities go home");if(DEBUG_STACK)mStackSupervisor.validateTopActivitiesLocked();returnmStackSupervisor.resumeHomeActivity(prev);}
booleanstartHomeActivityLocked(intuserId){Intentintent=getHomeIntent();ActivityInfoaInfo=resolveActivityInfo(intent,STOCK_PM_FLAGS,userId);if(aInfo!=null){intent.setComponent(newComponentName(aInfo.applicationInfo.packageName,aInfo.name));// Don't do this if the home app is currently being// instrumented.aInfo=newActivityInfo(aInfo);aInfo.applicationInfo=getAppInfoForUser(aInfo.applicationInfo,userId);ProcessRecordapp=getProcessRecordLocked(aInfo.processName,aInfo.applicationInfo.uid,true);if(app==null||app.instrumentationClass==null){intent.setFlags(intent.getFlags()|Intent.FLAG_ACTIVITY_NEW_TASK);mStackSupervisor.startHomeActivity(intent,aInfo);}}}
// Start the process. It will either succeed and return a result containing// the PID of the new process, or else throw a RuntimeException.Process.ProcessStartResultstartResult=Process.start("android.app.ActivityThread",app.processName,uid,uid,gids,debugFlags,mountExternal,app.info.targetSdkVersion,app.info.seinfo,null);
publicstaticfinalProcessStartResultstart(finalStringprocessClass,finalStringniceName,intuid,intgid,int[]gids,intdebugFlags,intmountExternal,inttargetSdkVersion,StringseInfo,String[]zygoteArgs){try{returnstartViaZygote(processClass,niceName,uid,gid,gids,debugFlags,mountExternal,targetSdkVersion,seInfo,zygoteArgs);}catch(ZygoteStartFailedExex){Log.e(LOG_TAG,"Starting VM process through Zygote failed");thrownewRuntimeException("Starting VM process through Zygote failed",ex);}}
booleanrunOnce()throwsZygoteInit.MethodAndArgsCaller{...try{if(pid==0){// in childIoUtils.closeQuietly(serverPipeFd);serverPipeFd=null;handleChildProc(parsedArgs,descriptors,childPipeFd,newStderr);// should never get here, the child is expected to either// throw ZygoteInit.MethodAndArgsCaller or exec().returntrue;}else{// in parent...pid of < 0 means failureIoUtils.closeQuietly(childPipeFd);childPipeFd=null;returnhandleParentProc(pid,descriptors,serverPipeFd,parsedArgs);}}finally{IoUtils.closeQuietly(childPipeFd);IoUtils.closeQuietly(serverPipeFd);}...}
staticvoidinvokeStaticMain(ClassLoaderloader,StringclassName,String[]argv)throwsZygoteInit.MethodAndArgsCaller{...cl=loader.loadClass(className);m=cl.getMethod("main",newClass[]{String[].class});.../* * This throw gets caught in ZygoteInit.main(), which responds * by invoking the exception's run() method. This arrangement * clears up all the stack frames that were required in setting * up the process. */thrownewZygoteInit.MethodAndArgsCaller(m,argv);}