​​Android​​系统服务线程都驻留在SystemServer进程中,由SystemServer启动,在SystemServer.init2函数中,通过启动一个线程来启动各种系统服务线程。

[java] ​​view plain​​ ​​copy​​

 

  1. public static final void init2() {  
  2. "Entered the Android system server!");  
  3. new ServerThread();// 创建一个线程  
  4. "android.server.ServerThread");//设置线程名称  
  5.         thr.start();/启动该线程  
  6.     }  

android系统服务都是在thr线程的run函数中启动:

[java] ​​view plain​​ ​​copy​​

 

  1. public void run() {  
  2.     EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,SystemClock.uptimeMillis());  
  3.   
  4. //创建一个消息循环对象  
  5.   
  6.     android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  7. true);  
  8. false);  
  9. // Critical services...  
  10. try {  
  11. "Activity Manager");  
  12. //①启动ActivityManagerService服务线程  
  13.         context = ActivityManagerService.main(factoryTest);  
  14.         ................................................  
  15. //②向ServiceManager注册自己  
  16.         ActivityManagerService.setSystemProcess();  
  17.         ................................................  
  18. "System Content Providers");  
  19. //③安装系统Providers  
  20.         ActivityManagerService.installSystemProviders();  
  21.         ................................................  
  22. //④设置ActivityManagerService的成员变量mWindowManager  
  23.         ActivityManagerService.self().setWindowManager(wm);  
  24.         ................................................  
  25. catch (RuntimeException e) {  
  26. "System", "******************************************");  
  27. "System", "************ Failure starting core service", e);  
  28.                  }  
  29. //⑤调用systemReady函数为系统准备各种服务  
  30. new Runnable() {  
  31. public void run() {  
  32. "Making services ready");  
  33.   
  34.                 startSystemUi(contextF);  
  35. try {  
  36. if (batteryF != null) batteryF.systemReady();  
  37. catch (Throwable e) {  
  38. "making Battery Service ready", e);  
  39.                 }  
  40. try {  
  41. if (networkManagementF != null) networkManagementF.systemReady();  
  42. catch (Throwable e) {  
  43. "making Network Managment Service ready", e);  
  44.                 }  
  45. try {  
  46. if (networkStatsF != null) networkStatsF.systemReady();  
  47. catch (Throwable e) {  
  48. "making Network Stats Service ready", e);  
  49.                 }  
  50. try {  
  51. if (networkPolicyF != null) networkPolicyF.systemReady();  
  52. catch (Throwable e) {  
  53. "making Network Policy Service ready", e);  
  54.                 }  
  55. try {  
  56. if (connectivityF != null) connectivityF.systemReady();  
  57. catch (Throwable e) {  
  58. "making Connectivity Service ready", e);  
  59.                 }  
  60. try {  
  61. if (dockF != null) dockF.systemReady();  
  62. catch (Throwable e) {  
  63. "making Dock Service ready", e);  
  64.                 }  
  65. try {  
  66. if (usbF != null) usbF.systemReady();  
  67. catch (Throwable e) {  
  68. "making USB Service ready", e);  
  69.                 }  
  70. try {  
  71. if (uiModeF != null) uiModeF.systemReady();  
  72. catch (Throwable e) {  
  73. "making UI Mode Service ready", e);  
  74.                 }  
  75. try {  
  76. if (recognitionF != null) recognitionF.systemReady();  
  77. catch (Throwable e) {  
  78. "making Recognition Service ready", e);  
  79.                 }  
  80.                 Watchdog.getInstance().start();  
  81.   
  82. // It is now okay to let the various system services start their  
  83. // third party code...  
  84.   
  85. try {  
  86. if (appWidgetF != null) appWidgetF.systemReady(safeMode);  
  87. catch (Throwable e) {  
  88. "making App Widget Service ready", e);  
  89.                 }  
  90. try {  
  91. if (wallpaperF != null) wallpaperF.systemReady();  
  92. catch (Throwable e) {  
  93. "making Wallpaper Service ready", e);  
  94.                 }  
  95. try {  
  96. if (immF != null) immF.systemReady(statusBarF);  
  97. catch (Throwable e) {  
  98. "making Input Method Service ready", e);  
  99.                 }  
  100. try {  
  101. if (locationF != null) locationF.systemReady();  
  102. catch (Throwable e) {  
  103. "making Location Service ready", e);  
  104.                 }  
  105. try {  
  106. if (countryDetectorF != null) countryDetectorF.systemReady();  
  107. catch (Throwable e) {  
  108. "making Country Detector Service ready", e);  
  109.                 }  
  110. try {  
  111. if (throttleF != null) throttleF.systemReady();  
  112. catch (Throwable e) {  
  113. "making Throttle Service ready", e);  
  114.                 }  
  115. try {  
  116. if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();  
  117. catch (Throwable e) {  
  118. "making Network Time Service ready", e);  
  119.                 }  
  120. try {  
  121. if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();  
  122. catch (Throwable e) {  
  123. "making Text Services Manager Service ready", e);  
  124.                 }  
  125.             }  
  126.         });  
  127.     Looper.loop();  
  128. "System ServerThread is exiting!");  
  129. }  

第一:ActivityManagerService.main(factoryTest)

[java] ​​view plain​​ ​​copy​​

 

  1. public static final Context main(int factoryTest) {  
  2. //①启动AThread线程来创建ActivityManagerService实例  
  3. new AThread();  
  4.     thr.start();  
  5.   
  6. synchronized (thr) {  
  7. while (thr.mService == null) {  
  8. try {  
  9.                 thr.wait();  
  10. catch (InterruptedException e) {  
  11.             }  
  12.         }  
  13.     }  
  14. //将创建的ActivityManagerService实例保存到ActivityManagerService的静态变量mSelf  
  15.     ActivityManagerService m = thr.mService;  
  16.     mSelf = m;  
  17. //②创建ActivityThread实例并保存到ActivityManagerService的静态变量mSystemThread  
  18.     ActivityThread at = ActivityThread.systemMain();  
  19.     mSystemThread = at;  
  20.     Context context = at.getSystemContext();  
  21.     context.setTheme(android.R.style.Theme_Holo);  
  22.     m.mContext = context;  
  23.     m.mFactoryTest = factoryTest;  
  24. //③创建一个ActivityStack实例,并保存到ActivityManagerService的成员变量mMainStack中  
  25. new ActivityStack(m, context, true);  
  26. //④向ServiceManager注册BatteryStatsService服务  
  27.     m.mBatteryStatsService.publish(context);  
  28. //⑤向ServiceManager注册UsageStatsService服务  
  29.     m.mUsageStatsService.publish(context);  
  30.       
  31. synchronized (thr) {  
  32. //取消AThread线程等待,进入消息循环状态  
  33. true;  
  34.         thr.notifyAll();  
  35.     }  
  36. //⑥调用startRunning函数  
  37. null, null, null, null);  
  38.       
  39. return context;  
  40. }  

 

①启动AThread线程

[java] ​​view plain​​ ​​copy​​

 

  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. //创建消息循环对象  
  11.         Looper.prepare();  
  12.         android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  13. false);  
  14. new ActivityManagerService();  
  15. synchronized (this) {  
  16. //创建ActivityManagerService实例  
  17.             mService = m;  
  18.             notifyAll();  
  19.         }  
  20. //mReady = false,所以该线程处于等待  
  21. synchronized (this) {  
  22. while (!mReady) {  
  23. try {  
  24.                     wait();  
  25. catch (InterruptedException e) {  
  26.                 }  
  27.             }  
  28.         }  
  29. // For debug builds, log event loop stalls to dropbox for analysis.  
  30. if (StrictMode.conditionallyEnableDebugLogging()) {  
  31. "Enabled StrictMode logging for AThread's Looper");  
  32.         }  
  33. //开启该线程的消息循环  
  34.         Looper.loop();  
  35.     }  
  36. }  

②创建ActivityThread实例

[java] ​​view plain​​ ​​copy​​

 

  1. public static final ActivityThread systemMain() {  
  2. true);  
  3. new ActivityThread();  
  4. true);  
  5. return thread;  
  6. }  

[java] ​​view plain​​ ​​copy​​

 

  1. private void attach(boolean system) {  
  2. //本地线程存储  
  3. this);  
  4. //mSystemThread=true  
  5. if (!system) {  
  6. new Runnable() {  
  7. public void run() {  
  8.                 ensureJitEnabled();  
  9.             }  
  10.         });  
  11. "<pre-initialized>");  
  12.         RuntimeInit.setApplicationObject(mAppThread.asBinder());  
  13.         IActivityManager mgr = ActivityManagerNative.getDefault();  
  14. try {  
  15.             mgr.attachApplication(mAppThread);  
  16. catch (RemoteException ex) {  
  17. // Ignore  
  18.         }  
  19. else {  
  20. // Don't set application object here -- if the system crashes,  
  21. // we can't display an alert, we just want to die die die.  
  22. "system_process");  
  23. try {  
  24. new Instrumentation();  
  25. new ContextImpl();  
  26. null, this);  
  27. //创建Application实例,并保存在成员变量mAllApplications中  
  28. class, context);  
  29.             mAllApplications.add(app);  
  30.             mInitialApplication = app;  
  31. //调用应用程序的onCreate函数  
  32.             app.onCreate();  
  33. catch (Exception e) {  
  34. throw new RuntimeException(  
  35. "Unable to instantiate Application():" + e.toString(), e);  
  36.         }  
  37.     }  
  38.       
  39. new ComponentCallbacks2() {  
  40. public void onConfigurationChanged(Configuration newConfig) {  
  41. synchronized (mPackages) {  
  42. // We need to apply this change to the resources  
  43. // immediately, because upon returning the view  
  44. // hierarchy will be informed about it.  
  45. if (applyConfigurationToResourcesLocked(newConfig, null)) {  
  46. // This actually changed the resources!  Tell  
  47. // everyone about it.  
  48. if (mPendingConfiguration == null ||  
  49.                             mPendingConfiguration.isOtherSeqNewer(newConfig)) {  
  50.                         mPendingConfiguration = newConfig;  
  51.                           
  52.                         queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);  
  53.                     }  
  54.                 }  
  55.             }  
  56.         }  
  57. public void onLowMemory() {  
  58.         }  
  59. public void onTrimMemory(int level) {  
  60.         }  
  61.     });  
  62. }  

③创建一个ActivityStack实例

[java] ​​view plain​​ ​​copy​​

 

  1. ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {  
  2.     mService = service;  
  3.     mContext = context;  
  4.     mMainStack = mainStack;  
  5.     PowerManager pm =(PowerManager)context.getSystemService(Context.POWER_SERVICE);  
  6. "ActivityManager-Sleep");  
  7. "ActivityManager-Launch");  
  8. false);  
  9. }  

④注册BatteryStatsService服务

[java] ​​view plain​​ ​​copy​​

 

  1. public void publish(Context context) {  
  2.     mContext = context;  
  3. "batteryinfo", asBinder());  
  4. new PowerProfile(mContext).getNumSpeedSteps());  
  5.     mStats.setRadioScanningTimeout(mContext.getResources().getInteger(  
  6.             com.android.internal.R.integer.config_radioScanningTimeout)* 1000L);  
  7. }  

⑤注册UsageStatsService服务

[java] ​​view plain​​ ​​copy​​

 

  1. public void publish(Context context) {  
  2.         mContext = context;  
  3.         ServiceManager.addService(SERVICE_NAME, asBinder());  
  4. }  

⑥调用startRunning函数startRunning(null, null, null, null)

[java] ​​view plain​​ ​​copy​​

 

  1. public final void startRunning(String pkg, String cls, String action,String data) {  
  2. synchronized(this) {  
  3. //mStartRunning = false  
  4. if (mStartRunning) {  
  5. return;  
  6.         }  
  7. true;  
  8. //mTopComponent=null  
  9. null && cls != null? new ComponentName(pkg, cls) : null;  
  10. //mTopAction=Intent.ACTION_MAIN  
  11. null ? action : Intent.ACTION_MAIN;  
  12. //mTopData=null  
  13.         mTopData = data;  
  14. if (!mSystemReady) {  
  15. return;  
  16.         }  
  17.     }  
  18. null);  
  19. }  

[java] ​​view plain​​ ​​copy​​

 

  1. public void systemReady(final Runnable goingCallback) {  
  2. //goingCallback = null  
  3. synchronized(this) {  
  4. //mSystemReady = false  
  5. if (mSystemReady) {  
  6. if (goingCallback != null) goingCallback.run();  
  7. return;  
  8.         }  
  9.           
  10. // mDidUpdate = false  
  11. if (!mDidUpdate) {  
  12. if (mWaitingUpdate) {  
  13. return;  
  14.             }  
  15. new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);  
  16. null;  
  17. try {  
  18. null, 0);  
  19. catch (RemoteException e) {  
  20.             }  
  21. if (ris != null) {  
  22. for (int i=ris.size()-1; i>=0; i--) {  
  23. if ((ris.get(i).activityInfo.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {  
  24.                         ris.remove(i);  
  25.                     }  
  26.                 }  
  27.                 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);  
  28.                   
  29.                 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();  
  30.                   
  31. final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();  
  32. for (int i=0; i<ris.size(); i++) {  
  33.                     ActivityInfo ai = ris.get(i).activityInfo;  
  34. new ComponentName(ai.packageName, ai.name);  
  35. if (lastDoneReceivers.contains(comp)) {  
  36.                         ris.remove(i);  
  37.                         i--;  
  38.                     }  
  39.                 }  
  40.   
  41. for (int i=0; i<ris.size(); i++) {  
  42.                     ActivityInfo ai = ris.get(i).activityInfo;  
  43. new ComponentName(ai.packageName, ai.name);  
  44.                     doneReceivers.add(comp);  
  45.                     intent.setComponent(comp);  
  46. null;  
  47. if (i == ris.size()-1) {  
  48. new IIntentReceiver.Stub() {  
  49. public void performReceive(Intent intent, int resultCode,  
  50. boolean ordered,  
  51. boolean sticky) {  
  52. // The raw IIntentReceiver interface is called  
  53. // with the AM lock held, so redispatch to  
  54. // execute our code without the lock.  
  55. new Runnable() {  
  56. public void run() {  
  57. synchronized (ActivityManagerService.this) {  
  58. true;  
  59.                                         }  
  60.                                         writeLastDonePreBootReceivers(doneReceivers);  
  61.                                         showBootMessage(mContext.getText(  
  62. false);  
  63.                                         systemReady(goingCallback);  
  64.                                     }  
  65.                                 });  
  66.                             }  
  67.                         };  
  68.                     }  
  69. "Sending system update to: " + intent.getComponent());  
  70. null, null, intent, null, finisher,  
  71. 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);  
  72. if (finisher != null) {  
  73. true;  
  74.                     }  
  75.                 }  
  76.             }  
  77. if (mWaitingUpdate) {  
  78. return;  
  79.             }  
  80. true;  
  81.         }  
  82.           
  83. true;  
  84. if (!mStartRunning) {  
  85. return;  
  86.         }  
  87.     }  
  88.   
  89. null;  
  90. synchronized(mPidsSelfLocked) {  
  91. for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {  
  92.             ProcessRecord proc = mPidsSelfLocked.valueAt(i);  
  93. if (!isAllowedWhileBooting(proc.info)){  
  94. if (procsToKill == null) {  
  95. new ArrayList<ProcessRecord>();  
  96.                 }  
  97.                 procsToKill.add(proc);  
  98.             }  
  99.         }  
  100.     }  
  101.       
  102. synchronized(this) {  
  103. if (procsToKill != null) {  
  104. for (int i=procsToKill.size()-1; i>=0; i--) {  
  105.                 ProcessRecord proc = procsToKill.get(i);  
  106. "Removing system update proc: " + proc);  
  107. true, false, "system update done");  
  108.             }  
  109.         }  
  110.           
  111. // Now that we have cleaned up any update processes, we  
  112. // are ready to start launching real processes and know that  
  113. // we won't trample on them any more.  
  114. true;  
  115.     }  
  116.       
  117. "System now ready");  
  118.     EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,SystemClock.uptimeMillis());  
  119.   
  120. synchronized(this) {  
  121. // Make sure we have no pre-ready processes sitting around.  
  122.           
  123. if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  124. new Intent(Intent.ACTION_FACTORY_TEST),STOCK_PM_FLAGS);  
  125. null;  
  126. if (ri != null) {  
  127.                 ActivityInfo ai = ri.activityInfo;  
  128.                 ApplicationInfo app = ai.applicationInfo;  
  129. if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {  
  130.                     mTopAction = Intent.ACTION_FACTORY_TEST;  
  131. null;  
  132. new ComponentName(app.packageName,  
  133.                             ai.name);  
  134. else {  
  135.                     errorMsg = mContext.getResources().getText(com.android.internal.R.string.factorytest_not_system);  
  136.                 }  
  137. else {  
  138.                 errorMsg = mContext.getResources().getText(com.android.internal.R.string.factorytest_no_action);  
  139.             }  
  140. if (errorMsg != null) {  
  141. null;  
  142. null;  
  143. null;  
  144.                 Message msg = Message.obtain();  
  145.                 msg.what = SHOW_FACTORY_ERROR_MSG;  
  146. "msg", errorMsg);  
  147.                 mHandler.sendMessage(msg);  
  148.             }  
  149.         }  
  150.     }  
  151.   
  152.     retrieveSettings();  
  153.   
  154. if (goingCallback != null) goingCallback.run();  
  155.       
  156. synchronized (this) {  
  157. if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  158. try {  
  159.                 List apps = AppGlobals.getPackageManager().getPersistentApplications(STOCK_PM_FLAGS);  
  160. if (apps != null) {  
  161. int N = apps.size();  
  162. int i;  
  163. for (i=0; i<N; i++) {  
  164.                         ApplicationInfo info= (ApplicationInfo)apps.get(i);  
  165. if (info != null &&!info.packageName.equals("android")) {  
  166.                             addAppLocked(info);  
  167.                         }  
  168.                     }  
  169.                 }  
  170. catch (RemoteException ex) {  
  171. // pm is in same process, this will never happen.  
  172.             }  
  173.         }  
  174.   
  175. // Start up initial activity.  
  176. true;  
  177.           
  178. try {  
  179. if (AppGlobals.getPackageManager().hasSystemUidErrors()) {  
  180.                 Message msg = Message.obtain();  
  181.                 msg.what = SHOW_UID_ERROR_MSG;  
  182.                 mHandler.sendMessage(msg);  
  183.             }  
  184. catch (RemoteException e) {  
  185.         }  
  186.   
  187. null);  
  188.     }  
  189. }  

第二:ActivityManagerService.setSystemProcess()

[java] ​​view plain​​ ​​copy​​

 

  1. public static void setSystemProcess() {  
  2. try {  
  3.         ActivityManagerService m = mSelf;  
  4.           
  5. "activity", m);  
  6. "meminfo", new MemBinder(m));  
  7. "gfxinfo", new GraphicsBinder(m));  
  8. if (MONITOR_CPU_USAGE) {  
  9. "cpuinfo", new CpuBinder(m));  
  10.         }  
  11. "permission", new PermissionController(m));  
  12. //把应用程序框架层下面的android包加载进来  
  13. "android", STOCK_PM_FLAGS);  
  14.         mSystemThread.installSystemApplicationInfo(info);  
  15.      
  16. synchronized (mSelf) {  
  17.             ProcessRecord app = mSelf.newProcessRecordLocked(  
  18.                     mSystemThread.getApplicationThread(), info,info.processName);  
  19. true;  
  20.             app.pid = MY_PID;  
  21.             app.maxAdj = ProcessList.SYSTEM_ADJ;  
  22.             mSelf.mProcessNames.put(app.processName, app.info.uid, app);  
  23. synchronized (mSelf.mPidsSelfLocked) {  
  24.                 mSelf.mPidsSelfLocked.put(app.pid, app);  
  25.             }  
  26. true, true);  
  27.         }  
  28. catch (PackageManager.NameNotFoundException e) {  
  29. throw new RuntimeException(  
  30. "Unable to find android system package", e);  
  31.     }  
  32. }  

第三:ActivityManagerService.installSystemProviders()

[java] ​​view plain​​ ​​copy​​

 

  1. public static final void installSystemProviders() {  
  2.         List<ProviderInfo> providers;  
  3. synchronized (mSelf) {  
  4. "system", Process.SYSTEM_UID);  
  5.             providers = mSelf.generateApplicationProvidersLocked(app);  
  6. if (providers != null) {  
  7. for (int i=providers.size()-1; i>=0; i--) {  
  8.                     ProviderInfo pi = (ProviderInfo)providers.get(i);  
  9. if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {  
  10. "Not installing system proc provider " + pi.name  
  11. ": not system .apk");  
  12.                         providers.remove(i);  
  13.                     }  
  14.                 }  
  15.             }  
  16.         }  
  17. if (providers != null) {  
  18.             mSystemThread.installSystemProviders(providers);  
  19.         }  
  20.   
  21. new CoreSettingsObserver(mSelf);  
  22.   
  23.         mSelf.mUsageStatsService.monitorPackages();  
  24.     }  

第三:ActivityManagerService.systemReady()