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

Android消息传递机制

2016-05-07 13:13 489 查看

背景需求

在Android中,当遇到子线程需要刷新UI时,最常的做法就是handler,当然还有其他方便的方法如Android给我们提供的runOnUiThread(runnable)方法,但归根结底都是使用handler来刷新UI的。

Android消息传递原理

简单的讲

1. handler发送一条消息给当前线程的messagequeue;

2. MessageQueue接受并存储该消息;

messagequeue实际上是一个用单链表实现的队列

3. looper无限循环的从MessageQueue中取出一条消息,并回调msg的消费方法。

实际调用的是msg.target.dispatchMessage(msg)方法对msg进行处理。其中msg.target为发送该msg的handler。

源码解读

Handler

Handler在Android消息传递过程中,主要负责发送消息和处理事件。

当handler发送一条消息时,无论是使用handler.postXX()还是使用handler.sendXXX()最终调用的都是:

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


其中enqueueMessage()方法是执行单链表在队尾的插入操作,该方法主要完成的是向messagequeue中插入一条消息。

dispatchMessage(Message msg)方法:

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}


在looper.loop()方法中,调用该方法对消息msg进行处理。

几点说明:

msg.callback中的callback实际上是handler.post(runable r)中的r。

handleCallback代码:

private static void handleCallback(Message message) {
message.callback.run();
}


从这可以看出,handleCallback实际操作是调用r.run()方法,即调用post过来的线程的run方法执行该线程的逻辑。

2. mCallback :当我们创建一个handler对象时,handler有一个构造方法:


public Handler(Callback callback){
this(callback, false);
}


其中Callback是一个接口,即:

public interface Callback {
public boolean handleMessage(Message msg);
}


mCallback.handleMessage(msg)实际是调用2中构造方法中callback对象的handlermessage方法。

3 . 最后调用的 handleMessage(msg)方法实际上是我们自己构造一个handler时 @Override 的handleMessage(Message msg)方法。

需要特别指明的是:

handler.post(runnable r)实际执行在handler所在的线程中。

官方说明为:

*Causes the Runnable r to be added to the message queue.

* The runnable will be run on the thread to which this handler is

* attached. *

在view中也有类似的post(runnable r)方法,但该方法执行在UI线程中。

官方说明为:

Causes the Runnable to be added to the message queue.The runnable will be run on the user interface thread.

Looper

在一个线程中,只有一个Looper对象。Looper在实现上使用的是单例模式。

Looper.prepare()代码:

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


new Looper(quitAllowed)代码:

private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();//当前looper所在线程
}


在这里可以看出,looper的构造方法是私有的,表明当前Looper使用的是单例模式,只有在myLooper()方法中才返回,代码 :return sThreadLocal.get()

总结

Handler:发送message到messagequeue

Looper:为一个线程创建唯一的messagequeue;取出messagequeue中的消息进行消费。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 消息传递