天天看點

(1)ActivityThread分析

1. 入口。

曾經一直都說Activity的人口是onCreate方法。事實上android上一個應用的入口,應該是ActivityThread。和普通的java類一樣,入口是一個main方法。

public static final void main(String[] args) {

        SamplingProfilerIntegration.start();

       ……

        Looper.prepareMainLooper();

        if (sMainThreadHandler == null) {

            sMainThreadHandler = new Handler();

        }

        ActivityThread thread = new ActivityThread();

        thread.attach(false);

        Looper.loop();

        thread.detach();

        ……

        Slog.i(TAG, "Main thread of " + name + " is now exiting");

    }

以下細緻分析一下這個main方法。

2.Looper.prepareMainLooper();

ActivityThread事實上就是我們常常說的UI thread,也就是主線程。我們都知道主線程能夠使用Handler進行異步通信,由于主線程中已經建立了Looper,而這個Looper就是在這裡建立的。假設其它線程須要使用Handler通信,就要自己去建立Looper。

3. sMainThreadHandler = new Handler();

建立一個Handler。

4. ActivityThread thread = new ActivityThread();

建立ActivityThread 對象。

ActivityThread 有幾個比較重要的成員變量,會在建立ActivityThread對象時初始化。

(1)final ApplicationThread mAppThread = new ApplicationThread();

ApplicationThread繼承自ApplicationThreadNative, 而ApplicationThreadNative又繼承自Binder并實作了IApplicationThread接口。IApplicationThread繼承自IInterface。這是一個非常明顯的binder結構,用于于Ams通信。IApplicationThread接口定義了對一個程式(linux的程序)操作的接口。ApplicationThread通過binder與Ams通信,并将Ams的調用,通過以下的H類(也就是Hnalder)将消息發送到消息隊列,然後進行對應的操作,入activity的start,

stop。

(2)final H mH = new H();

          private final class H extends Handler

mH負責處理ApplicationThread發送到消息隊列的消息,比如:

public void handleMessage(Message msg) {

            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);

            switch (msg.what) {

                case LAUNCH_ACTIVITY: {

                    ActivityClientRecord r = (ActivityClientRecord)msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(

                            r.activityInfo.applicationInfo);

                    handleLaunchActivity(r, null);

                } break;

5. handleLaunchActivity(r, null);

從名字中就能夠看出,這裡就将進行啟動activity的工作了。

方法中主要調用了這一句:

Activity a = performLaunchActivity(r, customIntent);

6. performLaunchActivity()

進行了一些初始化和指派操作後,建立activity。

activity = mInstrumentation.newActivity(

                    cl, component.getClassName(), r.intent);

然後調用:

繼續閱讀