Handler是什么?
处理耗时任务,Java中咱们一般是通过开启线程来处理。
new Thread(new Runnable()).start();
但是在Android中更新UI元素必须在主线程处理,否则会抛异常(CalledFromWrongThreadException)。Android为此设计了Handler机制。
Handler官方文档:
A Handler allows you to send and process
Message
and Runnable objects associated with a thread'sMessageQueue
. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
Handler
每个Handler实例都会与一个线程以及线程的messageQueue关联,关联动作在Handler的内部构造方法中。
public Handler(Callback callback, boolean async) {
...
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
发送的消息最终是通过MessageQueue来接收处理。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
最终消息分发在dispatchMessage中。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在handleMessage中就可以进行具体的Message来更新UI了。
Looper
通过上面的分析咱们发现,Handler真正的消息处理是通过绑定Looper和messageQueue来实现的。
Looper又是什么呢?
看源码,Looper的构造方法中会创建MessageQueue消息队列对象。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
关键方法:
-
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)); }
prepare()创建Looper对象,并将Looper添加到ThreadLocal中。ThreadLocal上层用的比较少,只要知道它是用来管理线程作用域的就行。
-
Looper()
public static void loop() { .... final MessageQueue queue = me.mQueue; for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } .... try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } ... msg.recycleUnchecked(); } }
获取当前线程绑定的Looper的消息队列,死循环不断从消息队列中取出Message来处理,有消息就调用消息的target(Handler对象)来处理,最后回收Message。
-
quit()
public void quit() { mQueue.quit(false); }
Looper的quit会调用MessageQueue的quit方法,如果是非安全退出,直接移除所有的消息,如果是安全退出,移除执行时间点大于当前时间点的message。
使用注意点
每个Message的target都会引用handler对象,用于处理消息。mHandler会被发送的Message对象引用。因此从MainThread(GCRoot)到Handler对象可达,mHandler会被泄漏。只有当延迟的消息被处理以后才会释放mHandler对象。
(Notice:默认的Handler方法会获取当前线程的Looper,Activity中的Handler会持有主线程的Looper,因此发消息的时候,也是向主线程的Looper的MessageQueue添加消息)
解决Handler内存泄漏的问题有两种方式:
及时移除,比如说在Actiivty的onDestroy()调removeCallbacksAndMessages
-
在基类统一用弱引用包装使用
protected BaseHandler mBaseHandler = new BaseHandler(this); public static class BaseHandler extends Handler { private WeakReference<Activity> mActivityWeakReference; public BaseHandler(Activity ac) { mActivityWeakReference = new WeakReference<>(ac); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void handleMessage(Message msg) { Activity ac = mActivityWeakReference.get(); if(null != ac && !ac.isFinishing() && !ac.isDestroyed()) { if(ac instanceof BaseActivity) { ((BaseActivity) ac).handleMessage(ac,msg); } } } } protected void handleMessage(Activity ac,Message msg) { }