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

Android Handler 詳解:從原始碼看跨線程更新 UI 的本質

編輯:關於 Android 程式設計

Android 開發中經常使用 Handler 來實現「跨線程(Activity)更新 UI」。本文從原始碼角度回答兩個問題:為什麼用 Handler 就能跨線程更新 UI?為什麼跨線程更新 UI 一定要用 Handler?

一、Demo 展示

Demo1:用 Handler 更新 UI

界面上只有一個 TextView 和一個 Button。按下按鈕建立背景線程,該線程每秒更新一次 TextView,連續 10 次後結束。

public class MainActivity extends Activity {
    static final String TAG = "MainActivity";
    Handler handler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView text = (TextView) findViewById(R.id.txtHello);
        Button button = (Button) findViewById(R.id.btnRun);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    public void run() {
                        for (int i = 0; i < 10; i++) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = "item-" + i;
                            handler.sendMessage(msg);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String str = "unknow";
                switch (msg.what) {
                    case 1:
                        str = (String) msg.obj;
                        break;
                    default:
                        break;
                }
                text.setText(str);
                super.handleMessage(msg);
            }
        };
    }
}

Demo2:自製 ActivityThread 模擬 Activity

為了後續分析方便,用一個 LooperThread 來模擬 Activity:

public class ActivityThread extends Thread {
    static final String TAG = "LooperThread";
    public Handler mHandler = null;

    public ActivityThread() {
        super("LooperThread");
    }

    @Override
    public void run() {
        Looper.prepare();
        synchronized (this) {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.d(TAG, String.format("recv msg.what: %d in Thread: %s(%d)",
                            msg.what, Thread.currentThread().getName(),
                            Thread.currentThread().getId()));
                }
            };
            this.notify();
        }
        Looper.loop();
    }

    public void waitForHandlerReady() {
        try {
            synchronized (this) {
                while (mHandler == null) this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

二、為什麼 Handler 能跨線程更新 UI

以 Demo2 為例,涉及三個線程:GodActivity 線程、ActivityThread 線程(模擬 UI)、以及匿名線程 aThread。aThread 透過 Handler 更新 ActivityThread 的 UI,兩者的交互如下:

關鍵點:

· MessageQueue 透過 Message.next 維護鏈表結構(Java 的參照即指標)。

· ActivityThread 的消息循環被封裝在 Looper.loop() 內;Looper.prepare() 用於建立屬於當前線程的 Looper 與 MessageQueue。

· 每個 Message 可透過 target 指向一個 Handler,而 Handler 就是處理該 Message 的回呼。

Looper.prepare()

Looper 線程「三部曲」:

Looper.prepare();
new Handler() { /* override handleMessage() */ };
Looper.loop();
public static void prepare() {
    prepare(true);
}

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    mPtr = nativeInit();
}

sThreadLocal 是 ThreadLocal 型別,即線程私有資料(線程級別單例)。可理解為 Map<Thread, T> 的一層包裝:set(value) 時以當前線程物件為 key,因此每個線程各持有一份 value。可見 prepare() 讓 ActivityThread 透過 sThreadLocal 持有了一個 Looper,而 Looper 建構時又創建了 MessageQueue。

Handler()

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
    mLooper = Looper.myLooper();     // 取得當前線程(呼叫者)的 Looper
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;         // 引用 Looper() 中建立的 MessageQueue
    mCallback = callback;
    mAsynchronous = async;
}

public static Looper myLooper() {
    return sThreadLocal.get();       // 從該線程的「單例」取出 Looper
}

這段程式碼解釋了一個常見錯誤的由來:在沒有呼叫 Looper.prepare() 的線程中建立 Handler 會直接拋出例外。

Looper.loop()

public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException(
            "No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;
    Binder.clearCallingIdentity();

    for (;;) {
        Message msg = queue.next();      // 取出消息,可能阻塞
        if (msg == null) {
            return;                      // 佇列正在關閉
        }
        msg.target.dispatchMessage(msg); // 透過 msg.target 分派消息
        msg.recycle();
    }
}

可見 for 迴圈就是「消息循環」:不斷從 MessageQueue 取出 Message,再交由 msg.target 派發。

如何 dispatch

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);             // 方法 1
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {   // 方法 2
                return;
            }
        }
        handleMessage(msg);              // 方法 3
    }
}

三種處理方式,優先級依次遞降,且一個 Message 只能採用其中一種:為 msg.callback 註冊 Runnable;為 Handler.mCallback 註冊 Handler.Callback;覆寫 handleMessage()。

Message 的發送與取得

// Handler 端
public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;               // 將當前 Handler 與 Message 綁定
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

這裡就是 Looper.loop() 中 target 的來源。MessageQueue.enqueueMessage() 是入隊操作,Message 依 when 大小排序:

synchronized (this) {
    if (mQuitting) {
        // 投递给已死亡線程上的 Handler,直接失敗
        return false;
    }
    msg.when = when;
    Message p = mMessages;
    boolean needWake;
    if (p == null || when == 0 || when < p.when) {
        // 新頭節點,需喚醒可能阻塞的事件佇列
        msg.next = p;
        mMessages = msg;
        needWake = mBlocked;
    } else {
        // 插入佇列中段
        needWake = mBlocked && p.target == null && msg.isAsynchronous();
        Message prev;
        for (;;) {
            prev = p;
            p = p.next;
            if (p == null || when < p.when) break;
            if (needWake && p.isAsynchronous()) needWake = false;
        }
        msg.next = p;
        prev.next = msg;
    }
    if (needWake) {
        nativeWake(mPtr);            // 通知前台線程「有消息來了」
    }
}

而 Looper.loop() 呼叫的 MessageQueue.next() 則負責出隊:

Message next() {
    for (;;) {
        nativePollOnce(mPtr, nextPollTimeoutMillis);   // 等待通知,可能阻塞
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message msg = mMessages;
            if (msg != null) {
                if (now < msg.when) {
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    mMessages = msg.next;
                    msg.next = null;      // 與 MessageQueue「斷絕關係」
                    msg.markInUse();
                    return msg;
                }
            }
            if (mQuitting) {
                dispose();
                return null;
            }
            // 佇列空閒時執行 IdleHandler,此處省略
        }
    }
}

三、小結:為什麼能跨線程

MessageQueue.next() 與 sendMessage() 分別被 Activity 線程與背景線程呼叫,兩者可能同時操作,因此共享並修改的成員變數需要加鎖——這正是 synchronized (this) 出現的原因。

歸根結底:Activity 線程背後都有一個消息佇列,背景線程透過 Handler.sendMessage 把消息放上去;Activity 線程取下消息後,交由具體 Handler 的 handleMessage 處理,而更新 UI 的程式碼就在其中。

所以 Handler 並未真正「跨線程」更新 UI——它只是把「要更新什麼」(Message 攜帶)與「如何更新」(Handler 攜帶)透過消息佇列傳達給 UI 線程,UI 線程才是真正的執行者。

四、真正的 ActivityThread

Demo2 的 ActivityThread 是虛構的,但真實情況也確實如此。驗證方式有兩種:查看 Activity 原始碼在執行 onCreate 前是否呼叫 Looper.prepare();以及在 onXXX 方法中打斷點觀察 CallStack。

從呼叫棧可以清楚看到 Looper.loop,且是由 ActivityThread.main 呼叫的:

public static void main(String[] args) {
    Looper.prepareMainLooper();          // 與 Looper.prepare 類似
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

五、Native 層:pipe + epoll 的喚醒機制

MessageQueue 中還留了幾個 native 方法:nativeInit、nativePollOnce、nativeWake。它們對應到:

static JNINativeMethod gMessageQueueMethods[] = {
    { "nativeInit",     "()I",   (void*)android_os_MessageQueue_nativeInit },
    { "nativeDestroy",  "(I)V",  (void*)android_os_MessageQueue_nativeDestroy },
    { "nativePollOnce", "(II)V", (void*)android_os_MessageQueue_nativePollOnce },
    { "nativeWake",     "(I)V",  (void*)android_os_MessageQueue_nativeWake },
    { "nativeIsIdling", "(I)Z",  (void*)android_os_MessageQueue_nativeIsIdling }
};

NativeMessageQueue 繼承 C++ 層的 MessageQueue,其建構中取得(或建立)線程私有的 Looper:

NativeMessageQueue::NativeMessageQueue() : mInCallback(false), mExceptionObj(NULL) {
    mLooper = Looper::getForThread();
    if (mLooper == NULL) {
        mLooper = new Looper(false);
        Looper::setForThread(mLooper);
    }
}

sp<Looper> Looper::getForThread() {
    pthread_once(& gTLSOnce, initTLSKey);
    return (Looper*)pthread_getspecific(gTLSKey);
}

C++ 層以 pthread_setspecific / pthread_getspecific / pthread_key_create 實現線程私有的 Looper 參照,與 Java 層的 ThreadLocal 異曲同工。

而 Looper 的建構揭示了喚醒機制的全貌——pipe + epoll:

Looper::Looper(bool allowNonCallbacks) : mAllowNonCallbacks(allowNonCallbacks) {
    int wakeFds[2];
    pipe(wakeFds);                        // 建立管道
    mWakeReadPipeFd  = wakeFds[0];
    mWakeWritePipeFd = wakeFds[1];
    fcntl(mWakeReadPipeFd,  F_SETFL, O_NONBLOCK);
    fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);

    mEpollFd = epoll_create(EPOLL_SIZE_HINT);   // IO 多路復用
    struct epoll_event eventItem;
    memset(& eventItem, 0, sizeof(epoll_event));
    eventItem.events = EPOLLIN;
    eventItem.data.fd = mWakeReadPipeFd;
    epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
}

nativeWake 的實作非常單純,只是向 pipe 寫端寫一個位元組:

void Looper::wake() {
    ssize_t nWrite;
    do {
        nWrite = write(mWakeWritePipeFd, "W", 1);
    } while (nWrite == -1 && errno == EINTR);
}

nativePollOnce 最終走到 pollInner,關鍵就是 epoll_wait:

int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

if (fd == mWakeReadPipeFd) {
    if (epollEvents & EPOLLIN) {
        awoken();     // 讀走 pipe 中的資料,確認被喚醒
    }
}

而 awoken() 讀出的內容被丟進一個暫時 buffer 就不管了——這再次證明這個 pipe 只作「喚醒通知」之用,並不關心實際內容:

void Looper::awoken() {
    char buffer[16];
    ssize_t nRead;
    do {
        nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
    } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
}

六、總結與引申

後台線程使用 Handler 更新 UI,本質上就是生產者消費者問題:後台線程是生產者,生產 Message 放進佇列;前台線程是消費者,從佇列取消息並處理。

Handler 在其中扮演兩個角色:一是消息佇列的窗口(sendMessage 入隊),二是處理消息的回呼(handleMessage 消費)。

最後談一點引申。本文兩個 Demo 都是「單生產者單消費者」。其中消費者必然唯一——每個線程最多只能有一個 Looper(由 Looper.prepare 建立),而 MessageQueue 由 Looper 建構方法創建,因此不可能有多個消費者線程共享同一個 MessageQueue。

但生產者可以不唯一。Demo1 中,按下按鈕後不到 10 秒再按一次,就會再建立一個背景線程,此時兩個線程都是生產者,有興趣可自行實測。

pipe 只有讀寫兩端:多生產者時有多個線程向寫端 write,但始終只有一個線程從讀端 read。因此 nativePollOnce 本可實作為阻塞式(讀端不必設為 NONBLOCK,也就不需要 epoll);但由於寫端可能被多個生產者同時寫入,設為 NONBLOCK 還是很必要的。

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