編輯:進階開發
本文追蹤的是「一個帶有 Activity 的 Android App 是怎麼被拉起來的」。答案埋在 Zygote 與 ActivityThread 的接力之中。
package dalvik.system;
class NativeStart implements Runnable {
private NativeStart() {}
private static native void main(String[] dummy);
public native void run();
}
這段程式透過 JNI 進一步激活 ZygoteInit 中的 main(),於是一個新的 Linux 進程就此誕生。不過在 Android 裡,Linux 的這些特性被層層封裝了起來,開發者只看得到 Activity、Service、ContentProvider、BroadcastReceiver 四種元件。
public static void main(String argv[]) {
try {
registerZygoteSocket();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis());
preloadClasses();
preloadResources();
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis());
// Do an initial gc to clean up after startup
gc();
if (argv.length != 2) {
throw new RuntimeException("ZygoteInit.main expects two arguments");
}
if (argv[1].equals("true")) {
startSystemServer();
}
Log.i(TAG, "Accepting command socket connections");
if (ZYGOTE_FORK_MODE) {
runForkMode();
} else {
runSelectLoopMode();
}
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}
關鍵設計在 MethodAndArgsCaller:它是一個同時繼承 Exception 又實作 Runnable 的類別,用來當「跳板」,把設定進程時所需的堆疊框架全部丟掉。
/**
* Helper exception class which holds a method and arguments and
* can call them. This is used as part of a trampoline to get rid of
* the initial process setup stack frames.
*/
public static class MethodAndArgsCaller extends Exception implements Runnable {
private final Method mMethod;
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
當 MethodAndArgsCaller 被拋出並在 main() 中被攔下時,執行的是 caller.run(),也就是 mMethod.invoke(null, new Object[] { mArgs })。這行呼叫激活了 ActivityThread 的 main 函式;由於它是 static 方法,invoke 的第一個參數才會是 null。
答案是 startSystemServer()。它準備好一組寫死的參數,fork 出系統服務進程。
/**
* Prepare the arguments and fork for the system server process.
*/
private static boolean startSystemServer()
throws MethodAndArgsCaller, RuntimeException {
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,3001,3002,3003",
"--capabilities=130104352,130104352",
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
int debugFlags = parsedArgs.debugFlags;
if ("1".equals(SystemProperties.get("ro.debuggable")))
debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids, debugFlags, null);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
handleSystemServerProcess(parsedArgs);
}
return true;
}
/**
* Finish remaining work for the newly forked system server process.
*/
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
if (parsedArgs.uid != 0) {
try {
setCapabilities(parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IOException ex) {
Log.e(TAG, "Error setting capabilities", ex);
}
}
closeServerSocket();
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
/* should never reach here */
}
子進程接著走 zygoteInit():重設標準輸出、執行共同初始化、呼叫 zygoteInitNative(),解析 --nice-name 等參數,最後把剩下的參數交給目標類別的靜態 main。
public static final void zygoteInit(String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
System.setOut(new androidPrintStream(Log.INFO, "System.out"));
System.setErr(new androidPrintStream(Log.WARN, "System.err"));
commonInit();
zygoteInitNative();
int curArg = 0;
for (; 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!");
return; // let the process exit
}
// 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);
}
private static void invokeStaticMain(String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
// 較積極地使用堆,避免佔用不必要的記憶體
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
Class cl;
try {
cl = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Missing class when invoking static main " + className, ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException("Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException("Main method is not public and static on " + className);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
把鏡頭拉遠看,整個流程就是:Zygote 預先載好類別與資源 → fork 出子進程 → 用一個「異常跳板」把無用的堆疊清掉 → 反射調用目標類別的靜態 main → ActivityThread 接手,你的 Activity 生命週期才正式開始。這個看似迂迴的設計,目的正是為了讓應用啟動時不必背著一長串設定進程的歷史包袱。
解析 Dalvik 虛擬機:Android 執行庫的分層與設計取捨
Dalvik 虛擬機隨著 Android 版本演進不斷強化。要理解它的設計,先要看清 Android 整體架構的位置。本文從系統分層談起,再看 Dalvik 在記憶體與檔
Android 語音辨識實作(1):讓手機聽懂你說什麼
當年 iPhone 上的語音功能,背後靠的是 Google 的技術。既然 Android 是 Google 自己力推的系統,把自家的核心能力放進來自然順理成章,再結合雲端
Android 測試框架實戰:從 TestSuite 到 Instrumentation
當程式取得根節點的參數後,就能直接透過節點進行失效化、測距與繪樹;而當你的 Activity 被啟用並取得焦點,真正的工作才開始——開發有用且吸引人的行動服務,並把產品推
消費者意向調查解讀:Android 從墊底到亞軍的翻身
Android 最初是 Google 開發、以 Linux 為基礎的開源手機作業系統,不存在以往那種牽絆產業創新的專有權障礙,並迅速成為智慧行動終端的作業系統選擇。 意