Android的消息處理機制主要分爲四個部分:oop
主要涉及三個類:post
Android應用程序每啓動一個線程,都爲其建立一個消息隊列,而後進入到一個無限循環之中。而後不斷檢查隊列中是否有新消息須要處理。若是沒有,線程就會進入睡眠狀態,反之會對消息進行分發處理。spa
下面根據上面所說的進行詳述。線程
整個建立過程涉及到兩個類:MessageQueue 和 Looper。它們在C++層有兩個對應的類:NativeMessageQueue和Looper。其關係以下圖所示:code
+------------+ +------+ |MessageQueue+----^+Looper| +-----+------+ +------+ | | | +-----------+------+ +------+ |NativeMessageQueue+^----+Looper| +------------------+ +------+ A----^B表示B中保存A的引用
建立過程以下所示:對象
+------+ +------------+ +------------------+ +--------------+ |Looper| |MessageQueue| |NativeMessageQueue| |Looper(Native)| +--+---+ +------+-----+ +---------+--------+ +-------+------+ | | | | | | | | +-------------------------------------------------------------------------------+ |[msg loop] | next() | | | | | +------------> | | | | | | | | | | | | | | | | | | | nativePollOnce() | | | | | | pollOnce() | | | | | +----------------> | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | pollOnce() | | | | | +-----------------> | | | | | | | | | | | | | epoll_wait() | | | | +--------+ | | | | | | | | | | | | | | | | | | | | <------+ | | | | | | awoken() | | + + + + | | | | | +-------------------------------------------------------------------------------+
+-------+ +------------+ +------------------+ +--------------+ |Handler| |MessageQueue| |NativeMessageQueue| |Looper(Native)| +--+----+ +-----+------+ +---------+--------+ +-------+------+ | | | | | | | | sendMessage()| | | | +----------> | | | | | | | | |enqueueMessage()| | | +--------------> | | | | | | | | | | | | | | | | | nativeWake() | | | | wake() | | | +------------------> | | | | | | | | | wake() | | | +------------------> | | | | | | | | | | | | |write(mWakeWritePipeFd, "W", 1) | | | | | | | | | | | | | | | | | | | | + + + +
消息發送過程主要由Handler對象來驅動。隊列
+------+ +-------+ |Looper| |Handler| +--+---+ +---+---+ | | | | loop() | | [after next()] | +---------> | | | | |dispatchMessage() +-------------> | | | | | | | handleMessage() | +-------+ | | | | | | | | <-----+ | | (callback or subclass) | | + +
Looper對象的loop方法裏面的queue.next方法若是返回了message,那麼handler的dispatchMessage會被調用。
a. 若是新建Handler的時候傳入了callback實例,那麼callback的handleMessage方法會被調用。
b. 若是是經過post方法向handler傳入runnable對象的,那麼runnable對象的run方法會被調用。
c. 其餘狀況下,handler方法的handleMessage會被調用。事件