Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

從 Zygote 到 ActivityThread:Android 應用啟動流程追蹤

編輯:進階開發

本文追蹤的是「一個帶有 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 四種元件。

ZygoteInit.main:預載資源的起點

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 與 invokeStaticMain

子進程接著走 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 生命週期才正式開始。這個看似迂迴的設計,目的正是為了讓應用啟動時不必背著一長串設定進程的歷史包袱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved