本文基於android 28 源碼
com.android.internal.os.ZygoteInit.java
com.android.internal.os.ZygoteServer.java
com.android.internal.os.ZygoteConnection.java
android.os.ZygoteProcess.java
在ZygoteInit.java源碼的main函數中創建 zygoteServer對象並 並註冊服務Socket
ZygoteServer zygoteServer = new ZygoteServer(); zygoteServer.registerServerSocketFromEnv(socketName);
然後調用 forkSystemServer 創建SystemServer
try{
caller = zygoteServer.runSelectLoop(abiList);//等待AMS客戶端 連接,並返回 Runnable } catch (Throwable ex) { Log.e(TAG, "System zygote died with exception", ex); throw ex; } finally { zygoteServer.closeServerSocket(); } // We're in the child process and have exited the select loop. Proceed to execute the // command. if (caller != null) { caller.run(); }
/* * Pass the remaining arguments to SystemServer. */ return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
接着調用靜態方法findStaticMain,傳入全路徑類名,參數和 類加載器
最終實例化MethodAndArgsCaller 類 並反射調用SystemServer 的 main 函數,如果不爲空則調用其 run函數
接着往下看 zygoteServer.runSelectLoop(abiList) 中 部分源碼,
args = readArgumentList(); 讀取客戶端 socket 參數
只有一處返回Runnable便是 ZygoteConnection的processOneCommand 函數
接着執行 Zygote.forkAndSpecialize 函數
返回如果這是child,pid=0
如果這是parent,pid=-1
接着執行 handleChildProc 函數 啓動 時parsedArgs.invokeWith 爲空( 即沒有添加--invoke-with) 執行else
這兩個分支最終都是 調用 findStaticMain 函數 創建 MethodAndArgsCaller 對象 返回 Runnable
最終在 ZygoteInit中調用 執行run函數
if (caller != null) { caller.run(); }
至此成功調用 到 ActivityThread 的main 函數