Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 內核剖析:Activity 的啟動流程

編輯:關於 Android 程式設計

我們每天寫 startActivity(),但這個方法背後到底走了哪些路徑?這篇順著源碼把一條啟動鏈路串起來。

一、兩個關鍵角色

  • ActivityThread:每個應用進程的啟動入口。系統每拉起一個 App,就會建立一條 ActivityThread 線程,負責維護該應用內所有四大組件。
  • ActivityManagerService(文中以 ActivityServiceManager 稱之):系統服務端,統籌所有 Activity 的管理與生命週期調度。

兩者透過 Binder 與 Handler 訊息機制協作:AMS 決定要啟動哪個 Activity,然後把啟動訊息發給目標進程的 ActivityThread。

二、scheduleLaunchActivity:把請求排入佇列

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
        ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
        List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
    ActivityClientRecord r = new ActivityClientRecord();
    r.token = token;
    r.ident = ident;
    r.intent = intent;
    r.activityInfo = info;
    r.state = state;
    r.pendingResults = pendingResults;
    r.pendingIntents = pendingNewIntents;
    r.startsNotResumed = notResumed;
    r.isForward = isForward;
    queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}

注意它把啟動所需的所有資訊打包進 ActivityClientRecord,再交給 queueOrSendMessage 排入主線程的 MessageQueue——這一步只是排隊,真正的動作在主線程空閒時才會發生。

三、handleMessage:主線程消費訊息

public void handleMessage(Message msg) {
    switch (msg.what) {
        case LAUNCH_ACTIVITY: {
            ActivityClientRecord r = (ActivityClientRecord) msg.obj;
            r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo);
            handleLaunchActivity(r, null);
        }
        break;
        // ... 其他訊息類型
    }
}

四、handleLaunchActivity:創建並恢復

private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    unscheduleGcIdler();          // 即將回到前台,取消背景 GC

    Activity a = performLaunchActivity(r, customIntent);   // 核心:真正建立 Activity

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        Bundle oldState = r.state;
        handleResumeActivity(r.token, false, r.isForward);

        if (!r.activity.mFinished && r.startsNotResumed) {
            // AMS 要求這個 Activity 啟動後先停在 paused 狀態(可見但不在前台)
            // 做法是先走一次完整啟動流程,再補一次 onPause
            r.activity.mCalled = false;
            mInstrumentation.callActivityOnPause(r.activity);
            r.state = oldState;   // 保留原始 state,以備重建時使用
            if (!r.activity.mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + r.intent.getComponent().toShortString()
                    + " did not call through to super.onPause()");
            }
            r.paused = true;
        }
    } else {
        // 啟動失敗,通知 AMS 取消
        try {
            ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null);
        } catch (RemoteException ex) { }
    }
}

五、performLaunchActivity:反射建立物件

這個方法很長,但骨架就是「反射 new 出物件 → attach 環境 → 依序回呼生命週期方法」。

private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, Context.CONTEXT_INCLUDE_CODE);
    }

    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }
    // 處理 alias 情況
    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity);
    }

    Activity activity = null;
    try {
        // 1. 用 ClassLoader 反射建立 Activity 實例
        ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        r.intent.setExtrasClassLoader(cl);
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to instantiate activity " + component, e);
    }

    try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            // 2. 建立 Context 並綁定
            ContextImpl appContext = new ContextImpl();
            appContext.init(r.packageInfo, r.token, this);
            appContext.setOuterContext(activity);

            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mConfiguration);

            // 3. attach:把 Context、ActivityThread、 Instrumentation、token 等塞進 Activity
            activity.attach(appContext, this, getInstrumentation(), r.token, r.ident,
                    app, r.intent, r.activityInfo, title, r.parent, r.embeddedID,
                    r.lastNonConfigurationInstance,
                    r.lastNonConfigurationChildInstances, config);

            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            // 4. 依序回呼生命週期
            activity.mCalled = false;
            mInstrumentation.callActivityOnCreate(activity, r.state);       // onCreate
            if (!activity.mCalled) {
                throw new SuperNotCalledException("Activity " + ... + " did not call through to super.onCreate()");
            }

            r.activity = activity;
            r.stopped = true;
            if (!r.activity.mFinished) {
                activity.performStart();                                    // onStart
                r.stopped = false;
            }
            if (!r.activity.mFinished && r.state != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
            }
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                mInstrumentation.callActivityOnPostCreate(activity, r.state); // onPostCreate
                if (!activity.mCalled) {
                    throw new SuperNotCalledException("Activity " + ... + " did not call through to super.onPostCreate()");
                }
            }
        }
        r.paused = true;
        mActivities.put(r.token, r);   // 以 token 為 key 記錄,供後續調度使用
    } catch (Exception e) {
        throw new RuntimeException("Unable to start activity " + component, e);
    }
    return activity;
}

六、幾個值得記住的細節

  • attach 做的事:把 ContextImpl、ActivityThread、Instrumentation、token 等一整套執行環境綁到 Activity 身上。所以在 onCreate 之前,Activity 就已經能用 getSystemService() 了。
  • Instrumentation 的角色:它內部持有 Activity 參照,所有生命週期回呼(callActivityOnCreate 等)都經由它轉一手,這也是單元測試能攔截生命週期的原因。
  • SuperNotCalledException:每個回呼後都檢查 activity.mCalled。若你在 onCreate 忘了呼叫 super.onCreate(),就是從這裡拋出來的。
  • onRestoreInstanceState 的時機:在 onStart 之後、onPostCreate 之前執行,這是 Activity 重建時恢復狀態的位置。
  • token 作為身份識別:mActivities.put(r.token, r) 之後,AMS 要 pause/stop/destroy 哪個 Activity,都是靠 token 找回對應的 record。

整條鏈路濃縮成一句話:AMS 決定 → 訊息進 ActivityThread 的 MessageQueue → 主線程取出 → 反射建立物件 → attach 環境 → 依序回呼 onCreate/onStart/onRestoreInstanceState → onResume。

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