Handler 简单使用
Handler Looper MessageQuene 源码解析
面试题
Handler 简单使用
Handler 一般用于android 中的线程之间的交互,一般写法:
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
//要做的操作...
}
};
new Runnable(){
@Override
public void run() {
Message message = Message.obtain();
...
mHandler.sendMessage(message);
}
};
那接下来我们看下,源码内部是经过怎样的调用最终调用到handleMessage 方法呢,怎么保证handleMessage 方法在Handler声明的线程中执行的呢
Handler Looper MessageQuene 源码解析
首先我们先对Looper MessageQuene 做下简单的介绍
- MessageQuene
指的是消息队列,即存放供handler处理的消息。MessageQueue主要包括两个操作:插入和读取。读取本身会伴随删除操作。虽然名字叫队列,但其实内部实现是通过单链表的形式实现的(单链表在插入和删除上比较有优势,不是连续存储) - Looper
Looper 开启消息循环系统,不断从消息队列 MessageQueue 取出消息交由 Handler 处理。
接下来我们首先根据sendMessage 的流程来进行解析,看下sendMessage 源码:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
我们可以看到sendMessage 调用的是sendMessageDelayed方法,我们自己也可以调用sendMessageDelayed ,指定msg 延迟多久执行
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
内部调用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);
}
sendMessageAtTime 方法首先获取mQueue<mQueue 是何时获取的?> ,然后通过enqueueMessage 将 msg 放到messagequeue 中,
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
首先我们看到将msg 的target 设置为this,即发送message 的Handler,然后将msg 通过 MessageQueue 的enqueueMessage 方法放入到MessageQueue 中。现在我们先看下MessageQueue 是何时获取的,以及下边用到的Looper 又是何时关联的:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
// 获取对应线程的looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 从looper中取出Messagequeue 赋值给Handler 中的mQueue
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
那么消息是如何从Messagequeue 中取出,之后又是怎么一步步将消息传到handleMessage进行处理的呢,这里就需要用到Looper了,上面我们介绍了Looper的作用,接下来我们看下具体实现代码
在我们创建线程时可以为每个线程绑定一个Looper ,线程中Looper 并不会自动创建,需要我们调用prepare 方法
Looper.prepare();
private static void prepare(boolean quitAllowed) {
// prepare 只能被调用一次,存放在static 的ThreadLocal中,
//也就是进程全局的,如果再初始化一次会把之前初始化的覆盖掉,导致之前的消息被丢掉
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
// 将looper 放到sThreadLocal 中,让Looper 和线程绑定
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
// 在looper 初始化时创建了MessageQueue ,在Handler 初始化时又将mQueue 传到了Handler中
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
ThreadLocal 不了解可以看下这篇文章ThreadLocal
之后我们通过loop 方法,开始循环的从queue 中取消息
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;
...
// 死循环保证一直从Message中取消息
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
//分发给target 的dispatchMessage 方法处理,target 即为我们分发消息的Handler
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
}
msg.recycleUnchecked();
}
}
loop 方法从Messagequeue 中取出消息,交有handler 的dispatchMessage 处理
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
由此就调到了我们复写的handleMessage 中,上面还有两个判断,也就是说只有上边的执行条件不符合时才会执行我们复写的handleMessage 方法。
我们来看下msg.callback 是什么,是什么时候赋值的
// 一个runnable
Runnable callback;
// 1. 用一个已有的消息初始化会将原来消息中的callback 赋值过来
public static Message obtain(Message orig) {
Message m = obtain();
m.what = orig.what;
m.arg1 = orig.arg1;
m.arg2 = orig.arg2;
m.obj = orig.obj;
m.replyTo = orig.replyTo;
m.sendingUid = orig.sendingUid;
m.workSourceUid = orig.workSourceUid;
if (orig.data != null) {
m.data = new Bundle(orig.data);
}
m.target = orig.target;
m.callback = orig.callback;
return m;
}
//2. 通过初始化时赋值
public static Message obtain(Handler h, Runnable callback) {
Message m = obtain();
m.target = h;
m.callback = callback;
return m;
}
// 3. 可以通过set设置
public Message setCallback(Runnable r) {
callback = r;
return this;
}
// 4. 最常见的使用post 发送消息时
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
mCallback 又是什么呢
// handler 中的内部接口
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
boolean handleMessage(@NonNull Message msg);
}
// 设置:通过两个参数的初始化方法可以进行设置
public Handler(@Nullable Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Handler 面试
- Handler MessageQueue Looper 的关联
- Handler 使用注意事项
- Handler sendMessage 流程
- MessageQueen 的数据结构和复用
扩展:
looper.loop 方法为什么不会造成anr
java 有几种引用类型及特点
HandlerThread
网友评论