Android的消息处理机制主要分为四个部分:
主要涉及三个类:
Android应用程序每启动一个线程,都为其创建一个消息队列,然后进入到一个无限循环之中。然后不断检查队列中是否有新消息需要处理。如果没有,线程就会进入睡眠状态,反之会对消息进行分发处理。
下面根据上面所说的进行详述。
整个创建过程涉及到两个类:MessageQueue 和 Looper。它们在C++层有两个对应的类:NativeMessageQueue和Looper。其关系如下图所示:
+------------+ +------+ |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会被调用。