We need start a new process when we tap application launcher or start a new service which is in a different process. This artical will describe how a new process is created but no matter whoever the caller is.

1.startProcessLocked in ActivityManagerService.java
Ignore rest of the function and focus on below code.

[c-sharp] view plain copy print ?
  1. int pid = Process.start("android.app.ActivityThread",

  2. mSimpleProcessManagement ? app.processName : null, uid, uid,

  3. gids, debugFlags, null);

int pid = Process.start("android.app.ActivityThread", mSimpleProcessManagement ? app.processName : null, uid, uid, gids, debugFlags, null);


According to above code,we can find that another process created with a nice name "app.processName" or NULL where the first args is the first class started by the new process.

Now, we look into the start function of the Process class.

2.startViaZygote in Process.java

[java] view plain copy print ?
  1. argsForZygote.add("--runtime-init");

  2. argsForZygote.add("--setuid=" + uid);

  3. argsForZygote.add("--setgid=" + gid);

argsForZygote.add("--runtime-init"); argsForZygote.add("--setuid=" + uid); argsForZygote.add("--setgid=" + gid);
The first sentence means that we need to init runtime when create this Process, the purpose of this initialization will be discussed later.
We should know the communication between ActivityManagerService and zygote relies on socket, AM writes the arguments of the new process into the buffer for zygote socket.
Then the starter's work is done, let's turn over into the zygote at looked at the other socket communication side.

3.
The zygote process will be in a loop in order to detect any connect into the zygote socket and fork the request process after being started by init deamon process, all this work is running in function runSelectLoopMode in ZygoteInit.java and calls runOnce function in ZygoteConnection.java to fork new process.

4.runOnce in ZygoteConnection.java

[c-sharp] view plain copy print ?
  1. pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid,

  2. parsedArgs.gids, parsedArgs.debugFlags, rlimits);

pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, rlimits);
Above code forks a new process, It is very easy to understand and unnecessary to look into.

[c-sharp] view plain copy print ?
  1. if (pid == 0) {

  2. // in child

  3. handleChildProc(parsedArgs, descriptors, newStderr);

  4. // should never happen

  5. returntrue;

  6. } else { /* pid != 0 */

  7. // in parent...pid of < 0 means failure

  8. return handleParentProc(pid, descriptors, parsedArgs);

  9. }

if (pid == 0) { // in child handleChildProc(parsedArgs, descriptors, newStderr); // should never happen return true; } else { /* pid != 0 */ // in parent...pid of < 0 means failure return handleParentProc(pid, descriptors, parsedArgs); }

As we know, parent process and child process will execute the code simultaneously after fork operation, therefore, the parent process will get the real pid of child process and call handleParentProc method, meanwhile, the child process will get a zero pid value and call handleChildProc.
We ignore the handleParentProc in which there is nothing important but cleanup of parent process.

The belowing operations are in the new process.

5.handleChildProc in ZygoteConnection.java

Function handleChildProc will check if the process starter needs the runtime initialization which is set in step 2. Here need to init runtime while every process is being created.

[c-sharp] view plain copy print ?
  1. if (parsedArgs.runtimeInit) {

  2. RuntimeInit.zygoteInit(parsedArgs.remainingArgs);

  3. }

if (parsedArgs.runtimeInit) { RuntimeInit.zygoteInit(parsedArgs.remainingArgs); }
6.zygoteInit in RuntimeInit.java

[c-sharp] view plain copy print ?
  1. publicstatic final void zygoteInit(String[] argv)

  2. throws ZygoteInit.MethodAndArgsCaller {

  3. // TODO: Doing this here works, but it seems kind of arbitrary. Find

  4. // a better place. The goal is to set it up for applications, but not

  5. // tools like am.

  6. System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));

  7. System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));


  8. commonInit();

  9. zygoteInitNative();


  10. int curArg = 0;

  11. for ( /* curArg */ ; curArg < argv.length; curArg++) {

  12. String arg = argv[curArg];


  13. if (arg.equals("--")) {

  14. curArg++;

  15. break;

  16. } elseif (!arg.startsWith("--")) {

  17. break;

  18. } elseif (arg.startsWith("--nice-name=")) {

  19. String niceName = arg.substring(arg.indexOf('=') + 1);

  20. Process.setArgV0(niceName);

  21. }

  22. }


  23. if (curArg == argv.length) {

  24. Slog.e(TAG, "Missing classname argument to RuntimeInit!");

  25. // let the process exit

  26. return;

  27. }


  28. // Remaining arguments are passed to the start class's static main


  29. String startClass = argv[curArg++];

  30. String[] startArgs = new String[argv.length - curArg];


  31. System.arraycopy(argv, curArg, startArgs, 0, startArgs.length);

  32. invokeStaticMain(startClass, startArgs);

  33. }

public static final void zygoteInit(String[] argv) throws ZygoteInit.MethodAndArgsCaller { // TODO: Doing this here works, but it seems kind of arbitrary. Find // a better place. The goal is to set it up for applications, but not // tools like am. System.setOut(new AndroidPrintStream(Log.INFO, "System.out")); System.setErr(new AndroidPrintStream(Log.WARN, "System.err")); commonInit(); zygoteInitNative(); int curArg = 0; for ( /* curArg */ ; curArg < argv.length; curArg++) { String arg = argv[curArg]; if (arg.equals("--")) { curArg++; break; } else if (!arg.startsWith("--")) { break; } else if (arg.startsWith("--nice-name=")) { String niceName = arg.substring(arg.indexOf('=') + 1); Process.setArgV0(niceName); } } if (curArg == argv.length) { Slog.e(TAG, "Missing classname argument to RuntimeInit!"); // let the process exit return; } // Remaining arguments are passed to the start class's static main String startClass = argv[curArg++]; String[] startArgs = new String[argv.length - curArg]; System.arraycopy(argv, curArg, startArgs, 0, startArgs.length); invokeStaticMain(startClass, startArgs); }
6.1 zygoteInitNative
This function is a native function which spawns a pool thread to detect binder IPCs. Its prototype in JNI layer is underlying:

[c-sharp] view plain copy print ?
  1. staticvoid com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)

  2. {

  3. gCurRuntime->onZygoteInit();

  4. }

static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz) { gCurRuntime->onZygoteInit(); }




gCurRuntime is a global variable which is initialized when app_main starts. We can find this process in AndroidRuntime constructor. So we confirm that the gCurRuntime is an AppRuntime instance and class AppRuntime extends AndroidRuntime.According to all the facts, we can conclude the onZygoteInit function belongs to class AppRuntime.

[c-sharp] view plain copy print ?
  1. virtualvoid onZygoteInit()

  2. {

  3. sp<ProcessState> proc = ProcessState::self();

  4. if (proc->supportsProcesses()) {

  5. LOGV("App process: starting thread pool./n");

  6. proc->startThreadPool();

  7. }

  8. }

virtual void onZygoteInit() { sp<ProcessState> proc = ProcessState::self(); if (proc->supportsProcesses()) { LOGV("App process: starting thread pool./n"); proc->startThreadPool(); } }
6.2 invokeStaticMain

After creating process and corresponding pool thread for binder IPC, the last job here is to call the "main" method of the process's first class. It should be "android.app.ActivityThread" for AM to start a new activity or service of different processes.
ActivityThread instance is the main thread of the new process.

7.main method in ActivityThread.java
[c-sharp] view plain copy print ?
  1. publicstatic final void main(String[] args) {

  2. SamplingProfilerIntegration.start();


  3. Process.setArgV0("<pre-initialized>");


  4. Looper.prepareMainLooper();

  5. if (sMainThreadHandler == null) {

  6. sMainThreadHandler = new Handler();

  7. }


  8. ActivityThread thread = new ActivityThread();

  9. thread.attach(false);


  10. if (false) {

  11. Looper.myLooper().setMessageLogging(new

  12. LogPrinter(Log.DEBUG, "ActivityThread"));

  13. }


  14. Looper.loop();


  15. if (Process.supportsProcesses()) {

  16. thrownew RuntimeException("Main thread loop unexpectedly exited");

  17. }


  18. thread.detach();

  19. String name = (thread.mInitialApplication != null)

  20. ? thread.mInitialApplication.getPackageName()

  21. : "<unknown>";

  22. Slog.i(TAG, "Main thread of " + name + " is now exiting");

  23. }

public static final void main(String[] args) { SamplingProfilerIntegration.start(); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); if (sMainThreadHandler == null) { sMainThreadHandler = new Handler(); } ActivityThread thread = new ActivityThread(); thread.attach(false); if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } Looper.loop(); if (Process.supportsProcesses()) { throw new RuntimeException("Main thread loop unexpectedly exited"); } thread.detach(); String name = (thread.mInitialApplication != null) ? thread.mInitialApplication.getPackageName() : "<unknown>"; Slog.i(TAG, "Main thread of " + name + " is now exiting"); } }
In above code, we can not find any sentence create the new activity or service. where is the operation hiding?

The implementation is very complicated, the above code has a sentence "thread.attach(false)" where all the stuff is hiding.

I will discuss how activity starts in later artical.




更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android(安卓)ImageView 白边 解决方案
  2. android自定义弹出层
  3. FragmentTabHost
  4. Android(安卓)QuickContactBadge联系人快
  5. NDK toolchain对应ABI
  6. Use guide for booting Android(安卓)on
  7. 标志FLAG_ACTIVITY_NEW_TASK的解释
  8. Kotlin简单开发-RecyclerView
  9. Android(安卓)BaseFragment基类
  10. ANDROID -- Bluetooth