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

Android 中 Activity 啟動過程的原始碼探究

編輯:關於 Android 程式設計

「Activity 是怎麼被啟動的」是理解 Android 框架的關鍵問題之一。本文透過逐步閱讀原始碼,追蹤從 ActivityThread 建立 Activity、Window 與 DecorView 的關聯,一路到 View 樹真正被 measure、layout、draw 顯示在螢幕上的完整過程。

一、performLaunchActivity:建立 Activity 物件

入口是 android.app.ActivityThread.performLaunchActivity(),以下是省略後的關鍵片段:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                    "Unable to instantiate activity " + component + ": " + e.toString(), e);
        }
    }

    try {
        if (activity != null) {
            activity.attach(appContext, this, getInstrumentation(), r.token, r.ident,
                    app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config);

            activity.mCalled = false;
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
    }
    ...
}

三個關鍵點:

  1. 透過 Instrumentation.newActivity(),依類名以反射方式建立 Activity 物件。
  2. 呼叫 activity.attach(),完成各種初始化綁定。
  3. 由 Instrumentation 執行 onCreate()。事實上,Activity 的所有生命週期方法都是由 Instrumentation 呼叫的——這也是它能作為測試框架攔截生命週期的設計基礎。

二、Activity.attach():Window 的誕生

final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config) {

    attachBaseContext(context);

    mFragments.attachActivity(this, mContainer, null);

    mWindow = PolicyManager.makeNewWindow(this);

    // ... 將各參數賦值給 Activity 的成員變數

    mWindow.setWindowManager(
            (WindowManager) context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);

    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    mCurrentConfig = config;
}

這裡做了幾件事:先建立 mWindow,再為它設定 WindowManager,最後把 WindowManager 存進 Activity 的 mWindowManager 欄位。

要注意的是,mWindow 的宣告型別是 Window,但實際物件是 PhoneWindow,它與 Activity 的內容顯示密切相關。

三、setContentView:Activity 只是轉發者

attach 完成後,onCreate() 自然被呼叫。而 onCreate 中通常呼叫的 setContentView(),並非由 Activity 自行實作:

public void setContentView(View view, ViewGroup.LayoutParams params) {
    getWindow().setContentView(view, params);
    initActionBar();
}

getWindow() 回傳的就是 attach 中賦值的 mWindow。Window 是一個抽象類別,setContentView() 在這裡沒有具體實作,真正的實作在 com.android.internal.policy.impl.PhoneWindow:

@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
    if (mContentParent == null) {
        installDecor();
    } else {
        mContentParent.removeAllViews();
    }
    mContentParent.addView(view, params);

    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

PhoneWindow 有兩個與視圖相關的成員:mDecor(DecorView)與 mContentParent(ViewGroup)。前者是整個視窗的根視圖,後者是應用內容的容器。

四、installDecor 與 generateLayout:視圖樹的搭建

private void installDecor() {
    if (mDecor == null) {
        mDecor = generateDecor();
        ...
    }
    if (mContentParent == null) {
        mContentParent = generateLayout(mDecor);
        ...
    }
}

protected DecorView generateDecor() {
    return new DecorView(getContext(), -1);
}

DecorView 是 PhoneWindow 的內部類,繼承自 FrameLayout,作為整個視窗的根節點。真正複雜的是 generateLayout:

protected ViewGroup generateLayout(DecorView decor) {
    // ... 依樣式、主題、版本等設定視圖屬性

    int layoutResource;   // 用來 inflate 的資源 id
    // ... 依 Window 的 feature 選擇合適的版面,賦值給 layoutResource

    mDecor.startChanging();

    View in = mLayoutInflater.inflate(layoutResource, null);
    decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));

    // 找出系統內容容器
    ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
    if (contentParent == null) {
        throw new RuntimeException("Window couldn't find content container view");
    }

    // ... 設定背景、ActionBar 屬性

    mDecor.finishChanging();
    return contentParent;
}

這個方法關鍵地做了五件事:

  1. 依 FLAG 設定 LayoutParams。
  2. 依 FEATURE 選擇一個合適的系統版面(如 R.layout.screen_simple)賦值給 layoutResource。
  3. 把 layoutResource inflate 成 View,加入 DecorView。
  4. 用 findViewById(ID_ANDROID_CONTENT) 取得系統預留的內容容器。
  5. 把它回傳並存入 mContentParent。

五、對 PhoneWindow 的四點理解

  1. 一個 Activity 對應一個 PhoneWindow,是一對一的關係。從 Activity A 跳到 Activity B,B 會建立自己的 PhoneWindow。
  2. PhoneWindow 管理整個螢幕內容(不含最頂部的系統狀態列),因此它對應的是「一個頁面」的概念。
  3. PhoneWindow 同時管理 ActionBar 與內容主體。setContentView() 設定內容,setTitle() 等操作 ActionBar,requestFeature() 則是 ActionBar 相關特性的開關。這些都是 public 方法,正是留給應用開發者呼叫的。
  4. PhoneWindow 本身不是 View。真正的視圖是它的成員 mDecor,而 ActionBar 與 contentParent 都是以 findViewById 從 mDecor 中取出的子視圖。

六、addView 之後:視圖樹成形但尚未顯示

回到 setContentView,installDecor 執行完畢後就是 mContentParent.removeAllViews() 與 addView()。

addView 內部先呼叫 requestLayout()——但這個時候它沒有效果。原因是 View.requestLayout() 會把請求往上傳給 mParent,而此時 mDecor 的 mParent 尚未設定(要等到 ViewRootImpl.setView() 才會賦值),請求鏈中斷在半路。

接著 addViewInner() 把 child 加入自己的 View 陣列,並把 child 的 parent 標記為自己。至此,mDecor → mContentParent → 使用者版面 的樹狀結構搭建完成,但畫面上什麼都還沒出現。

七、handleResumeActivity:真正讓畫面出現

final void handleResumeActivity(IBinder token, boolean clearHide,
        boolean isForward, boolean reallyResume) {

    ActivityClientRecord r = performResumeActivity(token, clearHide);

    if (r != null) {
        final Activity a = r.activity;

        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);

            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;

            if (a.mVisibleFromClient) {
                a.mWindowAdded = true;
                wm.addView(decor, l);      // 關鍵
            }
        }
    }
}

先由 performResumeActivity() 透過 Instrumentation 呼叫 onResume(),接著執行至關重要的 wm.addView(decor, l)。

這個 wm 就是 Activity 的 mWindowManager(WindowManagerImpl),其大部分方法是代理給 WindowManagerGlobal:

public void addView(View view, ViewGroup.LayoutParams params,
        Display display, Window parentWindow) {
    ViewRootImpl root;
    View panelParentView = null;

    root = new ViewRootImpl(view.getContext(), display);
    view.setLayoutParams(wparams);

    mViews.add(view);
    mRoots.add(root);
    mParams.add(wparams);

    // 最後執行,因為它會觸發後續的訊息
    try {
        root.setView(view, wparams, panelParentView);
    } catch (RuntimeException e) {
        throw e;
    }
}

重點是 new 了一個 ViewRootImpl,然後呼叫它的 setView。

八、ViewRootImpl.setView:requestLayout 終於有效

/** We have one child */
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    synchronized (this) {
        if (mView == null) {
            mView = view;

            // 在加入 window manager 之前先排入第一次 layout,
            // 以確保在任何系統事件送達前完成 relayout
            requestLayout();

            view.assignParent(this);
        }
    }
}

注意 ViewRootImpl 並不是 View 的子類。它把傳入的 decor 存為 mView,作為整個視圖樹的根節點,並透過 view.assignParent(this) 把自己設為 decor 的 parent。

這一刻起,requestLayout() 終於有效了——因為 mDecor 知道自己的 parent 是誰,請求鏈得以完整傳遞到 ViewRootImpl,後續的 measure、layout、draw 三步才能啟動。

九、scheduleTraversals:一次完整的視圖遍歷

void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        ...
    }
}

ViewRootImpl.requestLayout() 先確認是否在主執行緒,接著呼叫 scheduleTraversals()。它會張開一個同步屏障(sync barrier),確保在這次 traversal 完成前,其他同步訊息不會插隊。

被 post 的 Runnable 其 run() 方法會呼叫 doTraversal(),後者再呼叫 performTraversals()。這個方法很長,核心是按序呼叫:

  1. performMeasure():測量,決定每個 View 的寬高。
  2. performLayout():配置,決定每個 View 的位置。
  3. performDraw():繪製,把內容畫到螢幕上。

小結

把整條鏈條串起來看:

ActivityThread.performLaunchActivity → new Activity → attach(建立 PhoneWindow 與 WindowManager)→ onCreate → setContentView → PhoneWindow.installDecor(建立 DecorView 與 mContentParent)→ addView(視圖樹成形,但 requestLayout 無效)→ 回到 handleResumeActivity → onResume → wm.addView → new ViewRootImpl → setView → assignParent → requestLayout 生效 → performTraversals(measure / layout / draw)。

整個過程花了兩天在 grepcode 上讀原始碼,最大的收穫是:只要原始碼看得夠仔細,多數「為什麼畫面會這樣」的疑問都能自己找出答案。至於這些機制與實際開發(例如自訂 View 的繪製時機、requestLayout 為何有時不生效)之間的連結,還需要更多實務經驗的累積。

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