Android 消息机制主要指 Handler 的运行机制,包括了 MessageQueue、Looper 和 Handler 的共同作用。其中 MessageQueue 以队列的形式对外提供插入和删除,它内部由单链表实现。Looper 的作用是处理 MessageQueue 中存储的消息。
通常,Handler 被我们用来更新 UI,有如下两种常见的用法
public class MainActivity extends AppCompactActivity implements View.OnClickListener {
...
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 进行 UI 操作
}
};
...
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
...
handler.sendMessage(message);
}
}).start();
}
}
或者
public class MainActivity extends AppCompactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
// 进行 UI 操作
}
});
}
}).start();
}
}
用法一
在子线程完成耗时操作后,通过 sendMessage 方法发送消息,回到 Handler 所在的主线程,通过 handleMessage 方法完成 UI 操作。
来看 sendMessage 和它的后续方法
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以看到,经过这几个方法,发送的消息最终都传入了 MessageQueue 的 enqueueMessage 方法中,于是我们找到 enqueueMessage 方法
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
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; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
在 enqueueMessage 方法中,它主要执行的是单链表的插入操作,并没有对消息队列里的消息执行,那执行操作在哪呢?开头说到 Looper 的作用是执行 MessageQueue 中的消息,于是找到 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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
可以看到,loop 方法是一个死循环,它会调用 MessageQueue 的 next 方法来获取新消息,当 next 方法返回空时会退出循环。来看 next 方法源码
Message next() {
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier.
// Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready.
// Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now,
Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (false) Log.v("MessageQueue", "Returning message: " + msg);
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
...
}
...
}
}
next 方法用 mMessage 管理消息队列。当消息队列不为空时,返回并删除当前消息,并将下一条消息置前。若消息队列为空,next 方法会一直阻塞,直到有新消息到来。那 next 方法何时返回空呢?当 Looper 的 quit 方法调用时,next 会返回空。因为当 Looper 调用 quit 方法,MessageQueue 的 quit 或 quitSafely 方法会被调用,此时消息队列会被标记为退出状态,next 判断到消息队列的状态便会返回空。
接着看 loop 方法,如果 next 方法返回了消息,它会调用msg.target.dispatchMessage(msg)
来处理,其中msg.target
就是发送消息的 Handler 对象。也就是说通过 sendMessage 方法发送的消息会来到 Handler 对象的 dispatchMessage 方法,来看 dispatchMessage 方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dispatchMessage 方法会检查 Message 的 callback 是否为空,不为空就通过 handleCallback 方法来处理消息。Message 的 callback 是一个 Runnable 对象,它实际上就是 post 方法传来的 Runnable 参数。在 handleCallback 方法中会执行传来的 Runnable 对象
private static void handleCallback(Message message) {
message.callback.run();
}
接着 dispatchMessage 方法会判断 mCallback 是否为空,若不为空,调用 mCallback 的 handleMessage 方法,若为空,则调用 Handler 的 handleMessage 方法。其中 mCallback 的 handleMessage 方法指的是通过 Callback 接口实现的 handleMessage 方法
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
就这样,通过 sendMessage 发送的消息最终回到了 handleMessage 方法进行处理。
用法二
在子线程中通过 post 方法传入一个 Runnable 对象,在该对象中实现 UI 操作。
来看 post 方法
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
这里使用了 sendMessageDelayed 方法发送了一条消息。getPostMessage 方法的作用是将 Runnable 对象转换成一条消息
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
sendMessageDelayed 方法经过的流程在上面已经分析过。最终,通过 post 传入的 Runnable 对象会来到 dispatchMessage 方法中,被 handleCallback 方法调用。
补充
在子线程中直接创建 Handler 会报错,正确的用法是
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
在主线程中不必这样,因为它会调用Looper.prepareMainLooper
方法来创建 Looper。
相关参考 郭霖的博客
网友评论