根Activity組件的啟動過程

圖例只描述了Activity組件在進程外的啟動過程,即從Launcher點擊圖標啟動MainActivity的過程。

MainActivity的啟動過程涉及到了三個進程。MainActivity組件、LauncherActivity組件和ActivityManagerService組件分別運行在不同的進程中。

Activity啟動過程

在第23步中會首先創(chuàng)建進程,流程如下圖


其中ActivityManagerService和Process運行在system_server進程中,啟動新的進程時,需要system_server與zygote進程進行socket通信,從而fork出新的進程。執(zhí)行RuntimeInit.zygoteInit() -> RuntimeInit.applicationInit() -> RuntimeInit.invokeStaticMain()

    public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
        redirectLogStreams();

        commonInit();
        nativeZygoteInit();
        applicationInit(targetSdkVersion, argv, classLoader);
    }
**RuntimeInit.invokeStaticMain()**
//className的值是“android.app.ActivityThread”
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        Class<?> cl;

        try {
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            ......  
        }

        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } catch (NoSuchMethodException ex) {
            ......
        } catch (SecurityException ex) {
            ......
        }
        ......
        /*
         * 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);
    }

注意
ActivityThread.main方法的執(zhí)行是通過拋異常的方式執(zhí)行的。拋出MethodAndrArgsCaller異常,一直按照原路向上拋。在ZygoteInit.main方法中捕獲異常,并調(diào)用run方法反射執(zhí)行ActivityThread.main方法

public class ZygoteInit {
    public static void main(String argv[]) {
        try {
            ......

            registerZygoteSocket(socketName);
            ......
            preload();
            ......
            if (startSystemServer) {
                startSystemServer(abiList, socketName);
            }

            runSelectLoop(abiList);

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            // 處理異常
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容