原文地址:

Android SystemServer学习

http://blog.csdn.net/cloudwu007/article/details/6701765

Linux内核启动后,Android系统启动有4个步骤;

(1)init进程启动

(2)Native服务启动

(3)System Server及Java服务启动

(4)Home启动


Init进程启动后,将根据init.rc及initXXX.rc的内容执行一系列的命令,包括创建mount目录,安装文件系统,设置属性,启动adb,systemserver,mediaserver


system/core/rootdir/init.rc 内容如下

# setup the global environment //设置环境变量 export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin export LD_LIBRARY_PATH /vendor/lib:/system/lib ... # Filesystem image public mount points. //mount文件系统 mkdir /mnt/obb 0700 root system mount tmpfs tmpfs /mnt/obb mode=0755,gid=1000 ...
# Define the oom_adj values for the classes of processes that can be # killed by the kernel. These are used in ActivityManagerService. setprop ro.FOREGROUND_APP_ADJ 0 ... service servicemanager /system/bin/servicemanager //在其他服务启动前必须启动ServiceManager class pre_zygote_services user system group system critical onrestart restart zygote onrestart restart media
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server //启动SystemServer class zygote_services socket zygote stream 666 onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart media onrestart restart netd service media /system/bin/mediaserver //启动mediaserver,启动多媒体相关的camera/playback等服务 class zygote_services user media group system audio camera graphics inet net_bt net_bt_admin net_raw mot_drm input mot_tpapi mot_secclkd mot_pwric mot_caif ioprio rt 4

代码中service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server将启动systemserver。



具体调用路径如下:


app_process主入口函数,启动system server时命令行为app_process -Xzygote /system/bin --zygote --start-system-server。

frameworks/base/cmds/app_process/app_main.cpp

int main(int argc, const char* const argv[]) { ... // Next arg is startup classname or "--zygote" if (i < argc) { arg = argv[i++]; if (0 == strcmp("--zygote", arg)) { //命令行必须含 --zygote bool startSystemServer = (i < argc) ? strcmp(argv[i], "--start-system-server") == 0 : false; //命令行是否含--start-system-server setArgv0(argv0, "zygote"); set_process_name("zygote"); runtime.start("com.android.internal.os.ZygoteInit", startSystemServer); //此处启动systemserver } else { ... }

启动ZygoteInit进程,以后所有的java进程均须通过此进程fork而成。


frameworks/base/core/jni/AndroidRuntime.cpp

void AndroidRuntime::start(const char* className, const bool startSystemServer) { ... /* start the virtual machine */ if (startVm(&mJavaVM, &env) != 0) goto bail; /* * Register android functions. */ if (startReg(env) < 0) { LOGE("Unable to register all android natives\n"); goto bail; } ... if (startClass == NULL) { LOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else { startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { LOGE("JavaVM unable to find main() in '%s'\n", className); /* keep going */ } else { env->CallStaticVoidMethod(startClass, startMeth, strArray); //调用com.android.internal.os.ZygoteInit的main()方法 } } bail: free(slashClassName); }


ZygoteInit进程入口函数:

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

public static void main(String argv[]) { try { VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024); ... registerZygoteSocket(); ... preloadClasses(); ... preloadResources(); // Do an initial gc to clean up after startup gc(); ... if (argv[1].equals("true")) { //只支持true参数 startSystemServer(); //此处启动systemserver } ... if (ZYGOTE_FORK_MODE) { //目前为false runForkMode(); } else { runSelectLoopMode(); //将在Loop中顺序处理以后的For请求 } closeServerSocket(); } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; } } 启动system server。
[cpp] view plain copy print ?
  1. privatestatic boolean startSystemServer()
  2. throws MethodAndArgsCaller, RuntimeException {
  3. /* Hardcoded command line to start the system server */
  4. String args[] = {
  5. "--setuid=1000",
  6. "--setgid=1000",
  7. ... "--capabilities=130104352,130104352",
  8. "--runtime-init",
  9. "--nice-name=system_server",
  10. "com.android.server.SystemServer",//指定要启动的类名
  11. };
  12. ZygoteConnection.Arguments parsedArgs = null;...
  13. try {
  14. parsedArgs = new ZygoteConnection.Arguments(args);
  15. ...
  16. /* Request to fork the system server process */
  17. pid = Zygote.forkSystemServer(//fork出进程
  18. parsedArgs.uid, parsedArgs.gid,
  19. parsedArgs.gids, debugFlags, null,
  20. parsedArgs.permittedCapabilities,
  21. parsedArgs.effectiveCapabilities);
  22. } catch (IllegalArgumentException ex) {
  23. throw new RuntimeException(ex);
  24. }
  25. /* For child process */
  26. if (pid == 0) {
  27. handleSystemServerProcess(parsedArgs); //在fork出的进程里执行systemserver启动
  28. }
  29. return true;
  30. }
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException { /* Hardcoded command line to start the system server */ String args[] = { "--setuid=1000", "--setgid=1000", ... "--capabilities=130104352,130104352", "--runtime-init", "--nice-name=system_server", "com.android.server.SystemServer", //指定要启动的类名 }; ZygoteConnection.Arguments parsedArgs = null;... try { parsedArgs = new ZygoteConnection.Arguments(args); ... /* Request to fork the system server process */ pid = Zygote.forkSystemServer( //fork出进程 parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { handleSystemServerProcess(parsedArgs); //在fork出的进程里执行systemserver启动 } return true; }


进程fork出来后,关闭socket并初始化进程

[cpp] view plain copy print ?
  1. private staticvoid handleSystemServerProcess(
  2. ZygoteConnection.Arguments parsedArgs)
  3. throws ZygoteInit.MethodAndArgsCaller {
  4. closeServerSocket();
  5. RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
  6. }
private static void handleSystemServerProcess( ZygoteConnection.Arguments parsedArgs) throws ZygoteInit.MethodAndArgsCaller { closeServerSocket(); RuntimeInit.zygoteInit(parsedArgs.remainingArgs); }


所有java进程的共同入口zygoteInit()。


frameworks/base/core/java/com/android/internal/os/RuntimeInit.java [cpp] view plain copy print ?
  1. public static final void zygoteInit(String[] argv)
  2. throws ZygoteInit.MethodAndArgsCaller {
  3. ...
  4. commonInit(); //初始化时区,设置agent
  5. zygoteInitNative(); //调用到[email protected]p -> gCurRuntime->onZygoteInit(),此处启动ThreadPool
  6. ...
  7. invokeStaticMain(startClass, startArgs); //调用com.android.server.SystemServer的main方法
  8. }
public static final void zygoteInit(String[] argv) throws ZygoteInit.MethodAndArgsCaller { ... commonInit(); //初始化时区,设置agent zygoteInitNative(); //调用到[email protected]p -> gCurRuntime->onZygoteInit(),此处启动ThreadPool ... invokeStaticMain(startClass, startArgs); //调用com.android.server.SystemServer的main方法 }


zygoteInitNative()将调用到JNI方法,并最终调用到onZygoteInit以启动进程池。

frameworks/base/cmds/app_process/app_main.cpp

[cpp] view plain copy print ?
  1. virtual void onZygoteInit()
  2. {
  3. sp<ProcessState> proc = ProcessState::self();
  4. if (proc->supportsProcesses()) {
  5. LOGV("App process: starting thread pool.\n");
  6. proc->startThreadPool(); //启动线程池处理Binder事件
  7. }
  8. }
virtual void onZygoteInit() { sp<ProcessState> proc = ProcessState::self(); if (proc->supportsProcesses()) { LOGV("App process: starting thread pool.\n"); proc->startThreadPool(); //启动线程池处理Binder事件 } }
systemServer进程主函数入口:

frameworks/base/services/java/com/android/server/SystemServer.java

[cpp] view plain copy print ?
  1. public staticvoid main(String[] args) {
  2. // The system server has to run all of the time, so it needs to be
  3. // as efficient as possible with its memory usage.
  4. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  5. System.loadLibrary("android_servers");//Load JNI library here that is used by SystemServer
  6. init1(args); //这里调用到[email protected]_android_server_SystemServer.cpp
  7. }
public static void main(String[] args) { ... // The system server has to run all of the time, so it needs to be // as efficient as possible with its memory usage. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer init1(args); //这里调用到[email protected]_android_server_SystemServer.cpp }
systemServer初始化函数1,用来启动进程内所有的native服务,因为其他java服务依赖这些服务。

frameworks/base/services/jni/com_android_server_SystemServer.cpp

[cpp] view plain copy print ?
  1. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
  2. {
  3. system_init();
  4. }
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz) { system_init(); }


frameworks/base/cmds/system_server/library/system_init.cpp

[cpp] view plain copy print ?
  1. extern "C" status_t system_init()
  2. {
  3. sp<ProcessState> proc(ProcessState::self());
  4. sp<IServiceManager> sm = defaultServiceManager();
  5. LOGI("ServiceManager: %p\n", sm.get());
  6. sp<GrimReaper> grim = new GrimReaper();
  7. sm->asBinder()->linkToDeath(grim, grim.get(), 0);
  8. char propBuf[PROPERTY_VALUE_MAX];
  9. property_get("system_init.startsurfaceflinger", propBuf,"1");
  10. if (strcmp(propBuf, "1") == 0) { //可以通过改变属性来设置SurfaceFlinger是否run在systemserver里
  11. // Start the SurfaceFlinger
  12. SurfaceFlinger::instantiate();
  13. }
  14. // Start the sensor service
  15. SensorService::instantiate(); //启动SensorService
  16. // On the simulator, audioflinger et al don't get started the
  17. // same way as on the device, and we need to start them here
  18. if (!proc->supportsProcesses()) {//在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建
  19. // Start the AudioFlinger
  20. AudioFlinger::instantiate();
  21. // Start the media playback service
  22. MediaPlayerService::instantiate();
  23. // Start the camera service
  24. CameraService::instantiate();
  25. // Start the audio policy service
  26. AudioPolicyService::instantiate();
  27. }
  28. AndroidRuntime* runtime = AndroidRuntime::getRuntime();
  29. runtime->callStatic("com/android/server/SystemServer","init2");//调用[email protected],在这里创建工作线程以启动各java服务并进入循环处理各service请求
  30. if (proc->supportsProcesses()) {
  31. ProcessState::self()->startThreadPool(); //启动线程池,注意:由于前面已经调用过startThreadPool,故此次调用不做任何事情
  32. IPCThreadState::self()->joinThreadPool(); //主线程加入到线程池里
  33. }
  34. return NO_ERROR;
  35. }
extern "C" status_t system_init() { sp<ProcessState> proc(ProcessState::self()); sp<IServiceManager> sm = defaultServiceManager(); LOGI("ServiceManager: %p\n", sm.get()); sp<GrimReaper> grim = new GrimReaper(); sm->asBinder()->linkToDeath(grim, grim.get(), 0); char propBuf[PROPERTY_VALUE_MAX]; property_get("system_init.startsurfaceflinger", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { //可以通过改变属性来设置SurfaceFlinger是否run在systemserver里 // Start the SurfaceFlinger SurfaceFlinger::instantiate(); } // Start the sensor service SensorService::instantiate(); //启动SensorService // On the simulator, audioflinger et al don't get started the // same way as on the device, and we need to start them here if (!proc->supportsProcesses()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建 // Start the AudioFlinger AudioFlinger::instantiate(); // Start the media playback service MediaPlayerService::instantiate(); // Start the camera service CameraService::instantiate(); // Start the audio policy service AudioPolicyService::instantiate(); } AndroidRuntime* runtime = AndroidRuntime::getRuntime(); runtime->callStatic("com/android/server/SystemServer", "init2");//调用[email protected],在这里创建工作线程以启动各java服务并进入循环处理各service请求 if (proc->supportsProcesses()) { ProcessState::self()->startThreadPool(); //启动线程池,注意:由于前面已经调用过startThreadPool,故此次调用不做任何事情 IPCThreadState::self()->joinThreadPool(); //主线程加入到线程池里 } return NO_ERROR; }

进程初始化函数init2,用来启动进程内所有的java服务。

frameworks/base/services/java/com/android/server/SystemServer.java

[cpp] view plain copy print ?
  1. public class SystemServer
  2. {
  3. public static finalvoid 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. }
public class SystemServer { public static final void init2() { Slog.i(TAG, "Entered the Android system server!"); Thread thr = new ServerThread(); //创建新线程 thr.setName("android.server.ServerThread"); thr.start(); //启动工作线程,在此线程启动各种服务 }

此工作线程(线程1)实现Java Service注册初始化及进入SystemServer事件处理循环。

[cpp] view plain copy print ?
  1. class ServerThread extends Thread {
  2. @Override
  3. public void run() {
  4. Looper.prepare(); //在此线程内处理system server相关消息
  5. android.os.Process.setThreadPriority(
  6. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  7. BinderInternal.disableBackgroundScheduling(true);
  8. android.os.Process.setCanSelfBackground(false);
  9. // Critical services...
  10. try {
  11. ServiceManager.addService("entropy",new EntropyService());//注册Service到ServiceManager
  12. power = new PowerManagerService();
  13. ServiceManager.addService(Context.POWER_SERVICE, power);
  14. context = ActivityManagerService.main(factoryTest); //注意:此处启动ActivityManagerService
  15. ...
  16. pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);
  17. ActivityManagerService.setSystemProcess();
  18. ...
  19. ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
  20. ActivityManagerService.installSystemProviders()
  21. ...
  22. wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);//启动Windows Manager
  23. ServiceManager.addService(Context.WINDOW_SERVICE, wm);
  24. ((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
  25. ...
  26. wm.systemReady(); //通知SystemReady
  27. power.systemReady();
  28. try {
  29. pm.systemReady();
  30. } catch (RemoteException e) {
  31. }
  32. ...
  33. // We now tell the activity manager it is okay to run third party
  34. // code. It will call back into us once it has gotten to the state
  35. // where third party code can really run (but before it has actually
  36. // started launching the initial applications), for us to complete our
  37. // initialization.
  38. ((ActivityManagerService)ActivityManagerNative.getDefault())
  39. .systemReady(new Runnable() {
  40. public void run() {
  41. if (statusBarF != null) statusBarF.systemReady2();
  42. if (batteryF != null) batteryF.systemReady();
  43. if (connectivityF != null) connectivityF.systemReady();
  44. if (dockF != null) dockF.systemReady();
  45. if (usbF != null) usbF.systemReady();
  46. if (uiModeF != null) uiModeF.systemReady();
  47. if (recognitionF != null) recognitionF.systemReady();
  48. Watchdog.getInstance().start();
  49. // It is now okay to let the various system services start their
  50. // third party code...
  51. if (appWidgetF != null) appWidgetF.systemReady(safeMode);
  52. if (wallpaperF != null) wallpaperF.systemReady();
  53. if (immF != null) immF.systemReady();
  54. if (locationF != null) locationF.systemReady();
  55. if (throttleF != null) throttleF.systemReady();
  56. }
  57. ...
  58. Looper.loop(); //进入循环,处理请求
  59. }
  60. }
class ServerThread extends Thread { @Override public void run() { Looper.prepare(); //在此线程内处理system server相关消息 android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); BinderInternal.disableBackgroundScheduling(true); android.os.Process.setCanSelfBackground(false); // Critical services... try { ServiceManager.addService("entropy", new EntropyService()); //注册Service到ServiceManager power = new PowerManagerService(); ServiceManager.addService(Context.POWER_SERVICE, power); context = ActivityManagerService.main(factoryTest); //注意:此处启动ActivityManagerService ... pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF); ActivityManagerService.setSystemProcess(); ... ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL); ActivityManagerService.installSystemProviders() ... wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL); //启动Windows Manager ServiceManager.addService(Context.WINDOW_SERVICE, wm); ((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm); ... wm.systemReady(); //通知SystemReady power.systemReady(); try { pm.systemReady(); } catch (RemoteException e) { } ... // We now tell the activity manager it is okay to run third party // code. It will call back into us once it has gotten to the state // where third party code can really run (but before it has actually // started launching the initial applications), for us to complete our // initialization. ((ActivityManagerService)ActivityManagerNative.getDefault()) .systemReady(new Runnable() { public void run() { if (statusBarF != null) statusBarF.systemReady2(); if (batteryF != null) batteryF.systemReady(); if (connectivityF != null) connectivityF.systemReady(); if (dockF != null) dockF.systemReady(); if (usbF != null) usbF.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.systemReady(safeMode); if (wallpaperF != null) wallpaperF.systemReady(); if (immF != null) immF.systemReady(); if (locationF != null) locationF.systemReady(); if (throttleF != null) throttleF.systemReady(); } ... Looper.loop(); //进入循环,处理请求 } }

ActivityManagerService主入口:

frameworks/base/services/java/com/android/server/am/ActivityManagerService.java


[java] view plain copy print ?
  1. <span style="font-size:18px;">publicstaticfinal Context main(int factoryTest) {
  2. AThread thr = new AThread();//创建工作线程2
  3. thr.start(); //启动线程
  4. synchronized (thr) {//等待</span><span style="font-size:16px;"><span style="font-size:18px;">ActivityManagerService对象创建完成
  5. while (thr.mService == null) {
  6. try {
  7. thr.wait();
  8. } catch (InterruptedException e) {
  9. }
  10. }
  11. }</span>
  12. ActivityManagerService m = thr.mService;
  13. mSelf = m;
  14. ActivityThread at = ActivityThread.systemMain(); //加载system应用,并把此线程(工作线程1)作为SystemServer进程的system线程
  15. mSystemThread = at;
  16. Context context = at.getSystemContext();
  17. m.mContext = context;
  18. m.mFactoryTest = factoryTest;
  19. m.mMainStack = new ActivityStack(m, context,true);
  20. m.mBatteryStatsService.publish(context);
  21. m.mUsageStatsService.publish(context);
  22. synchronized (thr) {
  23. thr.mReady = true;
  24. thr.notifyAll();
  25. }
  26. m.startRunning(null,null,null,null);//初始化变量并设置system ready为true
  27. return context;
  28. }</span>
<span style="font-size:18px;"> public static final Context main(int factoryTest) { AThread thr = new AThread(); //创建工作线程2 thr.start(); //启动线程 synchronized (thr) { //等待</span><span style="font-size:16px;"><span style="font-size:18px;">ActivityManagerService对象创建完成 while (thr.mService == null) { try { thr.wait(); } catch (InterruptedException e) { } } }</span> ActivityManagerService m = thr.mService; mSelf = m; ActivityThread at = ActivityThread.systemMain(); //加载system应用,并把此线程(工作线程1)作为SystemServer进程的system线程 mSystemThread = at; Context context = at.getSystemContext(); m.mContext = context; m.mFactoryTest = factoryTest; m.mMainStack = new ActivityStack(m, context, true); m.mBatteryStatsService.publish(context); m.mUsageStatsService.publish(context); synchronized (thr) { thr.mReady = true; thr.notifyAll(); } m.startRunning(null, null, null, null); //初始化变量并设置system ready为true return context; }</span>


线程2中作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息。

[java] view plain copy print ?
  1. static class AThreadextends Thread {
  2. ActivityManagerService mService;
  3. boolean mReady = false;
  4. public AThread() {
  5. super("ActivityManager");
  6. }
  7. public void run() {
  8. Looper.prepare();
  9. android.os.Process.setThreadPriority(
  10. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  11. android.os.Process.setCanSelfBackground(false);
  12. ActivityManagerService m = new ActivityManagerService();
  13. synchronized (this) {
  14. mService = m;
  15. notifyAll();
  16. }
  17. synchronized (this) {
  18. while (!mReady) {
  19. try {
  20. wait();
  21. } catch (InterruptedException e) {
  22. }
  23. }
  24. }
  25. Looper.loop();
  26. }
  27. }
static class AThread extends Thread { ActivityManagerService mService; boolean mReady = false; public AThread() { super("ActivityManager"); } public void run() { Looper.prepare(); android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); ActivityManagerService m = new ActivityManagerService(); synchronized (this) { mService = m; notifyAll(); } synchronized (this) { while (!mReady) { try { wait(); } catch (InterruptedException e) { } } } Looper.loop(); } }

ActivityThread.systemMain()将加载系统应用apk:


ActivityThread.java

[java] view plain copy print ?
  1. public static final ActivityThread systemMain() {
  2. ActivityThread thread = new ActivityThread();
  3. thread.attach(true);//加载system应用
  4. return thread;
  5. }
  6. private finalvoid attach(boolean system) {
  7. sThreadLocal.set(this);
  8. mSystemThread = system;
  9. if (!system) {...
  10. } else {
  11. // Don't set application object here -- if the system crashes,
  12. // we can't display an alert, we just want to die die die.
  13. android.ddm.DdmHandleAppName.setAppName("system_process");
  14. try {
  15. mInstrumentation = new Instrumentation();
  16. ContextImpl context = new ContextImpl();
  17. context.init(getSystemContext().mPackageInfo, null, this);
  18. Application app = Instrumentation.newApplication(Application.class, context);//创建Application对象并实例化android.app.Application对象
  19. mAllApplications.add(app);
  20. mInitialApplication = app;
  21. app.onCreate(); //调用onCreate
  22. } catch (Exception e) {
  23. throw new RuntimeException(
  24. "Unable to instantiate Application():" + e.toString(), e);
  25. }
  26. }
public static final ActivityThread systemMain() { ActivityThread thread = new ActivityThread(); thread.attach(true); //加载system应用 return thread; } private final void attach(boolean system) { sThreadLocal.set(this); mSystemThread = system; if (!system) {... } else { // Don't set application object here -- if the system crashes, // we can't display an alert, we just want to die die die. android.ddm.DdmHandleAppName.setAppName("system_process"); try { mInstrumentation = new Instrumentation(); ContextImpl context = new ContextImpl(); context.init(getSystemContext().mPackageInfo, null, this); Application app = Instrumentation.newApplication(Application.class, context); //创建Application对象并实例化android.app.Application对象 mAllApplications.add(app); mInitialApplication = app; app.onCreate(); //调用onCreate } catch (Exception e) { throw new RuntimeException( "Unable to instantiate Application():" + e.toString(), e); } }


ActivityManagerService.java

[java] view plain copy print ?
  1. public finalvoid 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. systemReady(null);//设置system ready为true,但此句似乎无用因为mSystemReady此时必然为true,故调用systemReady(null)什么事也不做
  17. }
public final void startRunning(String pkg, String cls, String action, String data) { synchronized(this) { if (mStartRunning) { return; } mStartRunning = true; mTopComponent = pkg != null && cls != null ? new ComponentName(pkg, cls) : null; mTopAction = action != null ? action : Intent.ACTION_MAIN; mTopData = data; if (!mSystemReady) { return; } } systemReady(null); //设置system ready为true,但此句似乎无用因为mSystemReady此时必然为true,故调用systemReady(null)什么事也不做 }

[java] view plain copy print ?
  1. public void systemReady(final Runnable goingCallback) {...
  2. synchronized(this) {
  3. if (mSystemReady) {
  4. if (goingCallback !=null) goingCallback.run();//如果有Runnable要运行
  5. return;
  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. ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
  28. final ArrayList<ComponentName> doneReceivers =new ArrayList<ComponentName>();
  29. for (int i=0; i<ris.size(); i++) {
  30. ActivityInfo ai = ris.get(i).activityInfo;
  31. ComponentName comp = new ComponentName(ai.packageName, ai.name);
  32. if (lastDoneReceivers.contains(comp)) {
  33. ris.remove(i);
  34. i--;
  35. }
  36. }
  37. for (int i=0; i<ris.size(); i++) {
  38. ActivityInfo ai = ris.get(i).activityInfo;
  39. ComponentName comp = new ComponentName(ai.packageName, ai.name);
  40. doneReceivers.add(comp);
  41. intent.setComponent(comp);
  42. IIntentReceiver finisher = null;
  43. if (i == ris.size()-1) {
  44. finisher = new IIntentReceiver.Stub() {
  45. publicvoid performReceive(Intent intent,int resultCode,
  46. String data, Bundle extras, boolean ordered,
  47. boolean sticky) {
  48. // The raw IIntentReceiver interface is called
  49. // with the AM lock held, so redispatch to
  50. // execute our code without the lock.
  51. mHandler.post(new Runnable() {
  52. publicvoid run() {
  53. synchronized (ActivityManagerService.this) {
  54. mDidUpdate = true;
  55. }
  56. writeLastDonePreBootReceivers(doneReceivers);
  57. systemReady(goingCallback);
  58. }
  59. });
  60. }
  61. };
  62. }
  63. broadcastIntentLocked(null,null, intent,null, finisher,
  64. 0, null, null,null,true,false, MY_PID, Process.SYSTEM_UID);
  65. if (finisher !=null) {
  66. mWaitingUpdate = true;
  67. }
  68. }
  69. }
  70. if (mWaitingUpdate) {
  71. return;
  72. }
  73. mDidUpdate = true;
  74. }
  75. mSystemReady = true; //置位
  76. // silent reboot bit will be off on normal power down
  77. if (mContext.getResources().getBoolean(com.android.internal.R.bool.config_poweron_sound)) {
  78. ConfigInfo.pwrSnd_setSilentreboot(1);
  79. } else if (mContext.getResources()
  80. .getBoolean(com.android.internal.R.bool.config_mute_poweron_sound)) {
  81. // Request that the next BootAnimation plays its sound.
  82. ConfigInfo.pwrSnd_setSilentreboot(0);
  83. }
  84. if (!mStartRunning) { //如果ActivityManagerService.startRunning已运行过,则无需继续
  85. return;
  86. }
  87. }
  88. ArrayList<ProcessRecord> procsToKill = null;
  89. synchronized(mPidsSelfLocked) {
  90. for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
  91. ProcessRecord proc = mPidsSelfLocked.valueAt(i);
  92. if (!isAllowedWhileBooting(proc.info)){//检查FLAG_PERSISTENT是否为真
  93. if (procsToKill ==null) {
  94. procsToKill = new ArrayList<ProcessRecord>();
  95. }
  96. procsToKill.add(proc); //如果应用未指明为persistent,则不能在system ready前运行
  97. }
  98. }
  99. }
  100. synchronized(this) {
  101. if (procsToKill !=null) {
  102. for (int i=procsToKill.size()-1; i>=0; i--) {
  103. ProcessRecord proc = procsToKill.get(i);
  104. Slog.i(TAG, "Removing system update proc: " + proc);
  105. removeProcessLocked(proc, true); //杀掉所有已运行的非persistent应用
  106. }
  107. }
  108. // Now that we have cleaned up any update processes, we
  109. // are ready to start launching real processes and know that
  110. // we won't trample on them any more.
  111. mProcessesReady = true;//为真时,才允许launch正常的应用
  112. }...
  113. synchronized(this) {
  114. // Make sure we have no pre-ready processes sitting around.
  115. ...
  116. retrieveSettings();
  117. if (goingCallback !=null) goingCallback.run();
  118. synchronized (this) {
  119. if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
  120. try {
  121. List apps = AppGlobals.getPackageManager().
  122. getPersistentApplications(STOCK_PM_FLAGS);
  123. if (apps != null) {
  124. int N = apps.size();
  125. int i;
  126. for (i=0; i<N; i++) {
  127. ApplicationInfo info
  128. = (ApplicationInfo)apps.get(i);
  129. if (info !=null &&
  130. !info.packageName.equals("android")) {
  131. addAppLocked(info); //启动所有标为persistent的且package名字为android的应用
  132. }
  133. }
  134. }
  135. } catch (RemoteException ex) {
  136. // pm is in same process, this will never happen.
  137. }
  138. }
  139. // Start up initial activity.
  140. mBooting = true;
  141. try {
  142. if (AppGlobals.getPackageManager().hasSystemUidErrors()) {//如果/data/system文件夹的uid和当前system UID不匹配
  143. Message msg = Message.obtain();
  144. msg.what = SHOW_UID_ERROR_MSG;
  145. mHandler.sendMessage(msg);
  146. }
  147. } catch (RemoteException e) {
  148. }
  149. mMainStack.resumeTopActivityLocked(null);//启动初始进程Home
  150. }
  151. }

更多相关文章

  1. Android(安卓)C++ 线程使用
  2. Fragment中跨线程调用控件的问题
  3. Android(安卓)studio http请求获取数据失败或者获取不到数据原因
  4. Android(安卓)RIL 架构学习总结 .
  5. Android(安卓)Activity 四种启动模式
  6. 终结篇:Android(安卓)startActivity原理分析(基于Android(安卓)8.
  7. Android的RemoteViews
  8. android多线程断点续传
  9. Android(安卓)Service 之StartService()

随机推荐

  1. Android反编译和二次打包实战
  2. Android无线调试――抛开USB数据线
  3. Android(安卓)面试必备 - http 与 https
  4. android 简单地设置Activity界面的跳转动
  5. unity, imageEffect在android上不显示的
  6. 《第一行代码》读完总结
  7. 将JavaFX运行到Android上
  8. android canvas常用的方法解析(一)
  9. 隐形成本巨大 微软点评Android六宗罪
  10. Android应用程序私有目录下文件操作总结