Android系统启动流程 六--system server启动

System server的启动过程参考下面流程图,具体细节可以参考zygote的启动过程。本文主要描述system server从初始化到启动Home的过程。

systemServer进程主函数入口:
frameworks/base/services/java/com/android/server/SystemServer.java
  1. public static void main(String[] args) {  
  2.   
  3.     // The system server has to run all of the time, so it needs to be  
  4.     // as efficient as possible with its memory usage.  
  5.     VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);  
  6.   
  7.     System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer  
  8.     init1(args);     //这里调用到android_server_SystemServer_init1@com_android_server_SystemServer.cpp  
  9. }  
systemServer初始化函数1,用来启动进程内所有的native服务,因为其他java服务依赖这些服务。
frameworks/base/services/jni/com_android_server_SystemServer.cpp
  1. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
  2. {  
  3.     system_init();  
  4. }  
frameworks/base/cmds/system_server/library/system_init.cpp
  1. extern "C" status_t system_init()  
  2. {  
  3.     sp<ProcessState> proc(ProcessState::self());  
  4.       
  5.     sp<IServiceManager> sm = defaultServiceManager();  
  6.     LOGI("ServiceManager: %p\n", sm.get());  
  7.       
  8.     sp<GrimReaper> grim = new GrimReaper();  
  9.     sm->asBinder()->linkToDeath(grim, grim.get(), 0);  
  10.       
  11.     char propBuf[PROPERTY_VALUE_MAX];  
  12.     property_get("system_init.startsurfaceflinger", propBuf, "1");  
  13.     if (strcmp(propBuf, "1") == 0) {        //可以通过改变属性来设置SurfaceFlinger是否run在systemserver里  
  14.         // Start the SurfaceFlinger  
  15.         SurfaceFlinger::instantiate();  
  16.     }  
  17.   
  18.     // Start the sensor service  
  19.     SensorService::instantiate();       //启动SensorService  
  20.   
  21.     // On the simulator, audioflinger et al don't get started the  
  22.     // same way as on the device, and we need to start them here  
  23.     if (!proc->supportsProcesses()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建  
  24.   
  25.         // Start the AudioFlinger  
  26.         AudioFlinger::instantiate();  
  27.   
  28.         // Start the media playback service  
  29.         MediaPlayerService::instantiate();  
  30.   
  31.         // Start the camera service  
  32.         CameraService::instantiate();  
  33.   
  34.         // Start the audio policy service  
  35.         AudioPolicyService::instantiate();  
  36.     }  
  37.       
  38.     AndroidRuntime* runtime = AndroidRuntime::getRuntime();  
  39.   
  40.     runtime->callStatic("com/android/server/SystemServer", "init2");//调用init2@SystemServer.java,在这里创建工作线程以启动各java服务并进入循环处理各service请求  
  41.           
  42.     if (proc->supportsProcesses()) {  
  43.         ProcessState::self()->startThreadPool();  //启动线程池,注意:由于前面已经调用过startThreadPool,故此次调用不做任何事情  
  44.         IPCThreadState::self()->joinThreadPool(); //主线程加入到线程池里  
  45.     }  
  46.     return NO_ERROR;  
  47. }  
进程初始化函数init2,用来启动进程内所有的java服务。
frameworks/base/services/java/com/android/server/SystemServer.java
  1. public class SystemServer  
  2. {  
  3.     public static final void init2() {  
  4.         Slog.i(TAG, "Entered the Android system server!");  
  5.         Thread thr = new ServerThread();               //创建新线程  
  6.         thr.setName("android.server.ServerThread");  
  7.         thr.start();     //启动工作线程,在此线程启动各种服务  
  8.     }  
此工作线程(线程1)实现Java Service注册初始化及进入SystemServer事件处理循环。
 
  1. class ServerThread extends Thread {  
  2.     @Override  
  3.     public void run() {  
  4.         Looper.prepare();          //在此线程内处理system server相关消息  
  5.   
  6.         android.os.Process.setThreadPriority(  
  7.                 android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  8.   
  9.         BinderInternal.disableBackgroundScheduling(true);  
  10.         android.os.Process.setCanSelfBackground(false);  
  11.          // Critical services...  
  12.         try {  
  13.             ServiceManager.addService("entropy", new EntropyService()); //注册Service到ServiceManager  
  14.             power = new PowerManagerService();  
  15.             ServiceManager.addService(Context.POWER_SERVICE, power);  
  16.             context = ActivityManagerService.main(factoryTest); //注意:此处启动ActivityManagerService  
  17.  ...  
  18.             pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);  
  19.             ActivityManagerService.setSystemProcess();  
  20. ...  
  21.             ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  22.             ActivityManagerService.installSystemProviders()  
  23. ...  
  24.             wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL); //启动Windows Manager  
  25.             ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  26.             ((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);  
  27. ...  
  28.          wm.systemReady();          //通知SystemReady  
  29.         power.systemReady();  
  30.         try {  
  31.             pm.systemReady();  
  32.         } catch (RemoteException e) {  
  33.         }  
  34. ...  
  35.         // We now tell the activity manager it is okay to run third party  
  36.         // code.  It will call back into us once it has gotten to the state  
  37.         // where third party code can really run (but before it has actually  
  38.         // started launching the initial applications), for us to complete our  
  39.         // initialization.  
  40.         ((ActivityManagerService)ActivityManagerNative.getDefault())  
  41.                 .systemReady(new Runnable() {  
  42.             public void run() {  
  43.                 if (statusBarF != null) statusBarF.systemReady2();  
  44.                 if (batteryF != null) batteryF.systemReady();  
  45.                 if (connectivityF != null) connectivityF.systemReady();  
  46.                 if (dockF != null) dockF.systemReady();  
  47.                 if (usbF != null) usbF.systemReady();  
  48.                 if (uiModeF != null) uiModeF.systemReady();  
  49.                 if (recognitionF != null) recognitionF.systemReady();  
  50.                 Watchdog.getInstance().start();  
  51.   
  52.                 // It is now okay to let the various system services start their  
  53.                 // third party code...  
  54.   
  55.                 if (appWidgetF != null) appWidgetF.systemReady(safeMode);  
  56.                 if (wallpaperF != null) wallpaperF.systemReady();  
  57.                 if (immF != null) immF.systemReady();  
  58.                 if (locationF != null) locationF.systemReady();  
  59.                 if (throttleF != null) throttleF.systemReady();  
  60.             }  
  61. ...  
  62.         Looper.loop(); //进入循环,处理请求  
  63.     }  
  64. }  
ActivityManagerService主入口:
frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
  1. <span style="font-size:18px;">    public static final Context main(int factoryTest) {  
  2.         AThread thr = new AThread();    //创建工作线程2  
  3.         thr.start();                    //启动线程  
  4.   
  5.         synchronized (thr) { //等待</span><span style="font-size:16px;"><span style="font-size:18px;">ActivityManagerService对象创建完成  
  6.             while (thr.mService == null) {  
  7.                 try {  
  8.                     thr.wait();  
  9.                 } catch (InterruptedException e) {  
  10.                 }  
  11.             }  
  12.         }</span>  
  13.         ActivityManagerService m = thr.mService;  
  14.         mSelf = m;  
  15.   
  16.         ActivityThread at = ActivityThread.systemMain(); //加载system应用,并把此线程(工作线程1)作为SystemServer进程的system线程  
  17.         mSystemThread = at;  
  18.         Context context = at.getSystemContext();  
  19.         m.mContext = context;  
  20.         m.mFactoryTest = factoryTest;  
  21.         m.mMainStack = new ActivityStack(m, context, true);  
  22.           
  23.         m.mBatteryStatsService.publish(context);  
  24.         m.mUsageStatsService.publish(context);  
  25.   
  26.         synchronized (thr) {  
  27.             thr.mReady = true;  
  28.             thr.notifyAll();  
  29.         }  
  30.   
  31.         m.startRunning(null, null, null, null); //初始化变量并设置system ready为true  
  32.           
  33.         return context;  
  34.     }</span>  
线程2中作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息。
  1. static class AThread extends Thread {  
  2.     ActivityManagerService mService;  
  3.     boolean mReady = false;  
  4.   
  5.     public AThread() {  
  6.         super("ActivityManager");  
  7.     }  
  8.   
  9.     public void run() {  
  10.         Looper.prepare();  
  11.   
  12.         android.os.Process.setThreadPriority(  
  13.                 android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  14.         android.os.Process.setCanSelfBackground(false);  
  15.   
  16.         ActivityManagerService m = new ActivityManagerService();  
  17.   
  18.         synchronized (this) {  
  19.             mService = m;  
  20.             notifyAll();  
  21.         }  
  22.   
  23.         synchronized (this) {  
  24.             while (!mReady) {  
  25.                 try {  
  26.                     wait();  
  27.                 } catch (InterruptedException e) {  
  28.                 }  
  29.             }  
  30.         }  
  31.   
  32.         Looper.loop();  
  33.     }  
  34. }  
ActivityThread.systemMain()将加载系统应用apk:
ActivityThread.java
  1.     public static final ActivityThread systemMain() {  
  2.         ActivityThread thread = new ActivityThread();  
  3.         thread.attach(true);           //加载system应用  
  4.         return thread;  
  5.     }  
  6.   
  7.     private final void attach(boolean system) {  
  8.         sThreadLocal.set(this);  
  9.         mSystemThread = system;  
  10.         if (!system) {...              
  11.         } else {  
  12.             // Don't set application object here -- if the system crashes,  
  13.             // we can't display an alert, we just want to die die die.  
  14.             android.ddm.DdmHandleAppName.setAppName("system_process");  
  15.             try {  
  16.                 mInstrumentation = new Instrumentation();  
  17.                 ContextImpl context = new ContextImpl();  
  18.                 context.init(getSystemContext().mPackageInfo, null, this);  
  19.                 Application app = Instrumentation.newApplication(Application.class, context); //创建Application对象并实例化android.app.Application对象  
  20.                 mAllApplications.add(app);  
  21.                 mInitialApplication = app;  
  22.                 app.onCreate();  //调用onCreate  
  23.             } catch (Exception e) {  
  24.                 throw new RuntimeException(  
  25.                         "Unable to instantiate Application():" + e.toString(), e);  
  26.             }  
  27.         }  
ActivityManagerService.java
  1. public final void startRunning(String pkg, String cls, String action,  
  2.         String data) {  
  3.     synchronized(this) {  
  4.         if (mStartRunning) {  
  5.             return;  
  6.         }  
  7.         mStartRunning = true;  
  8.         mTopComponent = pkg != null && cls != null  
  9.                 ? new ComponentName(pkg, cls) : null;  
  10.         mTopAction = action != null ? action : Intent.ACTION_MAIN;  
  11.         mTopData = data;  
  12.         if (!mSystemReady) {  
  13.             return;  
  14.         }  
  15.     }  
  16.   
  17.     systemReady(null);        //设置system ready为true,但此句似乎无用因为mSystemReady此时必然为true,故调用systemReady(null)什么事也不做  
  18. }  
    public void systemReady(final Runnable goingCallback) {...  
  1.         synchronized(this) {  
  2.             if (mSystemReady) {  
  3.                 if (goingCallback != null) goingCallback.run();  //如果有Runnable要运行  
  4.                 return;  
  5.             }  
  6.               
  7.             // Check to see if there are any update receivers to run.  
  8.             if (!mDidUpdate) {  
  9.                 if (mWaitingUpdate) {  
  10.                     return;  
  11.                 }  
  12.                 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);  
  13.                 List<ResolveInfo> ris = null;  
  14.                 try {  
  15.                     ris = AppGlobals.getPackageManager().queryIntentReceivers(  
  16.                                 intent, null, 0);  
  17.                 } catch (RemoteException e) {  
  18.                 }  
  19.                 if (ris != null) {  
  20.                     for (int i=ris.size()-1; i>=0; i--) {  
  21.                         if ((ris.get(i).activityInfo.applicationInfo.flags  
  22.                                 &ApplicationInfo.FLAG_SYSTEM) == 0) {  
  23.                             ris.remove(i);  
  24.                         }  
  25.                     }  
  26.                     intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);  
  27.                       
  28.                     ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();  
  29.                       
  30.                     final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();  
  31.                     for (int i=0; i<ris.size(); i++) {  
  32.                         ActivityInfo ai = ris.get(i).activityInfo;  
  33.                         ComponentName comp = new ComponentName(ai.packageName, ai.name);  
  34.                         if (lastDoneReceivers.contains(comp)) {  
  35.                             ris.remove(i);  
  36.                             i--;  
  37.                         }  
  38.                     }  
  39.                       
  40.                     for (int i=0; i<ris.size(); i++) {  
  41.                         ActivityInfo ai = ris.get(i).activityInfo;  
  42.                         ComponentName comp = new ComponentName(ai.packageName, ai.name);  
  43.                         doneReceivers.add(comp);  
  44.                         intent.setComponent(comp);  
  45.                         IIntentReceiver finisher = null;  
  46.                         if (i == ris.size()-1) {  
  47.                             finisher = new IIntentReceiver.Stub() {  
  48.                                 public void performReceive(Intent intent, int resultCode,  
  49.                                         String data, Bundle extras, boolean ordered,  
  50.                                         boolean sticky) {  
  51.                                     // The raw IIntentReceiver interface is called  
  52.                                     // with the AM lock held, so redispatch to  
  53.                                     // execute our code without the lock.  
  54.                                     mHandler.post(new Runnable() {  
  55.                                         public void run() {  
  56.                                             synchronized (ActivityManagerService.this) {  
  57.                                                 mDidUpdate = true;  
  58.                                             }  
  59.                                             writeLastDonePreBootReceivers(doneReceivers);  
  60.                                             systemReady(goingCallback);  
  61.                                         }  
  62.                                     });  
  63.                                 }  
  64.                             };  
  65.                         }  
  66.                         broadcastIntentLocked(null, null, intent, null, finisher,  
  67.                                 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);  
  68.                         if (finisher != null) {  
  69.                             mWaitingUpdate = true;  
  70.                         }  
  71.                     }  
  72.                 }  
  73.                 if (mWaitingUpdate) {  
  74.                     return;  
  75.                 }  
  76.                 mDidUpdate = true;  
  77.             }  
  78.               
  79.             mSystemReady = true;    //置位  
  80.             // silent reboot bit will be off on normal power down  
  81.             if (mContext.getResources().getBoolean(com.android.internal.R.bool.config_poweron_sound)) {  
  82.                 ConfigInfo.pwrSnd_setSilentreboot(1);  
  83.             } else if (mContext.getResources()  
  84.                     .getBoolean(com.android.internal.R.bool.config_mute_poweron_sound)) {  
  85.                 // Request that the next BootAnimation plays its sound.  
  86.                 ConfigInfo.pwrSnd_setSilentreboot(0);  
  87.             }  
  88.   
  89.             if (!mStartRunning) { //如果ActivityManagerService.startRunning已运行过,则无需继续  
  90.                 return;  
  91.             }  
  92.         }  
  93.   
  94.         ArrayList<ProcessRecord> procsToKill = null;  
  95.         synchronized(mPidsSelfLocked) {  
  96.             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {  
  97.                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);  
  98.                 if (!isAllowedWhileBooting(proc.info)){ //检查FLAG_PERSISTENT是否为真  
  99.                     if (procsToKill == null) {  
  100.                         procsToKill = new ArrayList<ProcessRecord>();  
  101.                     }  
  102.                     procsToKill.add(proc);        //如果应用未指明为persistent,则不能在system ready前运行  
  103.                 }  
  104.             }  
  105.         }  
  106.           
  107.         synchronized(this) {  
  108.             if (procsToKill != null) {  
  109.                 for (int i=procsToKill.size()-1; i>=0; i--) {  
  110.                     ProcessRecord proc = procsToKill.get(i);  
  111.                     Slog.i(TAG, "Removing system update proc: " + proc);  
  112.                     removeProcessLocked(proc, true);       //杀掉所有已运行的非persistent应用  
  113.                 }  
  114.             }  
  115.               
  116.             // Now that we have cleaned up any update processes, we  
  117.             // are ready to start launching real processes and know that  
  118.             // we won't trample on them any more.  
  119.             mProcessesReady = true;           //为真时,才允许launch正常的应用  
  120.         }...      
  121.         synchronized(this) {  
  122.             // Make sure we have no pre-ready processes sitting around.              
  123. ...   
  124.        retrieveSettings();  
  125.   
  126.         if (goingCallback != null) goingCallback.run();  
  127.           
  128.         synchronized (this) {  
  129.             if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  130.                 try {  
  131.                     List apps = AppGlobals.getPackageManager().  
  132.                         getPersistentApplications(STOCK_PM_FLAGS);  
  133.                     if (apps != null) {  
  134.                         int N = apps.size();  
  135.                         int i;  
  136.                         for (i=0; i<N; i++) {  
  137.                             ApplicationInfo info  
  138.                                 = (ApplicationInfo)apps.get(i);  
  139.                             if (info != null &&  
  140.                                     !info.packageName.equals("android")) {  
  141.                                 addAppLocked(info);         //启动所有标为persistent的且package名字为android的应用  
  142.                             }  
  143.                         }  
  144.                     }  
  145.                 } catch (RemoteException ex) {  
  146.                     // pm is in same process, this will never happen.  
  147.                 }  
  148.             }  
  149.   
  150.             // Start up initial activity.  
  151.             mBooting = true;  
  152.               
  153.             try {  
  154.                 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { //如果/data/system文件夹的uid和当前system UID不匹配  
  155.                     Message msg = Message.obtain();  
  156.                     msg.what = SHOW_UID_ERROR_MSG;  
  157.                     mHandler.sendMessage(msg);  
  158.                 }  
  159.             } catch (RemoteException e) {  
  160.             }  
  161.   
  162.             mMainStack.resumeTopActivityLocked(null); //启动初始进程Home  
  163.         }  
  164.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值