您的位置:首页 > 移动开发 > Android开发

浅谈Android Handler 消息机制

2016-01-25 17:20 429 查看
Handler是Android中提供的一种异步回调机制。

由于Android中的UI线程是基于单线程设计的,所以我们没办法在子线程中更新UI,并且不能在UI线程中执行耗时操作,使用Handler我们就能轻松解决这些问题。

Handler需要依赖于Looper、MessageQueue。接下来我们就来缕一缕这三者之间的关系,以及Handler的实现原理。

我们通常使用Handler的时候,一般会sendMessage或者post来发送一个消息,其实它们最终都会调用sendMessageAtTime()这个方法

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);
}


可以看到无论是sendMessage还是post,最终只是调用了MessageQueue的enqueueMessage()方法。而enqueueMessage()方法其实就是往MessageQueue放入了一个Message信息。接下来看下MessageQueue,从字面上看是消息队列的意思,但是去简单翻看一下Message的源码就可以发现,其实MessageQueue是基于单链表的数据结构来实现的,这也不难理解,MessageQueue面临大量的增删操作,链表的数据结构必然会比队列的效率要高的多。到这里Handler和MessageQueue的关系差不多理清了,当Handler通过sendMessage或者post方法发送消息是,其实就是往MessageQueue中添加了一条消息数据。有存必然会有取,在MessageQueue中有一个next源码如下:

Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
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);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
}


可以看到next方法返回了一个Message对象,而在next方法中则是一个阻塞方法不断的获取消息队列中的消息,一旦有消息立即返回。而这个取消息的操作则就是在Looper中执行,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);

}


loop方法中的逻辑也比较简单,其中是一个死循环,不断的从MessageQueue中调用next()方法获取Message对象,而next()方法是一个阻塞的方法,一旦有消息则会立即返回,最终调用dispatchMessage()实现异步回调操作。至此,Handler的处理过程结束。

最后再理一遍过程,当应用启动时,会创建一个Looper对象,执行loop方法,不断的从MessageQueue中获取消息。当我们使用Handler发送一个消息,会往MessageQueue中添加一条Message信息,这个消息会被Looper对象捕获,执行dispatchMessage回调方法,实现异步回调。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: