一、Handler机制
Handler在创建时,默认与当前所在线程的Looper绑定,也以一个线程的Looper作为参数创建Handler。一个线程只有一个对应的Looper(利用ThreadLocal来保证),Looper里有一个MessageQueue对象,handler可以将Message发送到MessageQueue中,Message进入队列中。而Looper是一个死循环,它不断的从MessageQueue中取出消息(调用MessageQueue的next方法,这时如果队头的消息延迟时间还没满,就发生阻塞),然后将这个消息分发。Message中有一个Target成员,用来绑定handler。消息分发后就会调用绑定的Handler中的dispatchMessage方法,从而调用初始化Handler时初始化的回调函数。
handler在调用sendMessage(Message msg)、post(Runnable r)等方法时,本质上最终都调用了:
sendMessageAtTime方法
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) uptimeMillis.
* The time-base is {@link android.os.SystemClock#uptimeMillis}.
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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在进行判断MessageQueue是否为空,mQueue即为Handler所在线程或传入的Looper的mQueue,然后调用Handler的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);
}
可以看到enqueueMessage方法中,将消息的target绑定了当前Handler。然后调用MessageQueue中的消息队列的enqueueMessage方法。
于是来看MessageQueue的enqueueMessage方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
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;
}
主要逻辑就是根据消息的when(即时间),来插入消息队列。消息队列是一个链表的结构,因此要将被插入的消息按照时间顺序插入合适的位置,也就是前面的时间比它前,后面的时间比它大的位置。
这样消息就进入了消息队列中。
再来看Looper的Loop函数。(关于Looper的loop死循环为什么不阻塞线程,与Linux系统的epoll机制有关,笔者目前还不是很了解)
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
注意看Message msg = queue.next()这一句代码,官方注释里说,这是可能阻塞的,也就是链表头时间还没到时出现的阻塞情况。我们看MessageQueue的next方法怎么实现的:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
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;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
代码比较长,将主要逻辑抽取出来,是这样的:
Message next() {
...
for (;;) {
//说明消息头还在准备
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
...
取出队列头msg
if (msg != null) {
if(当前消息没准备好){
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
}
else{
改变链表头
返回msg。
}
} else{
// No more messages.
nextPollTimeoutMillis = -1;
}
}
所以next方法是might block的,因为有可能阻塞在了for循环处。
接下来loop方法终于取出消息后,调用msg.target.dispatchMessage(msg);就分发了消息
于是回到Handler中,查看dispatchMessage(msg)函数:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
如果这个Message有绑定的Callback,就去handleCallback函数
private static void handleCallback(Message message) {
message.callback.run();
}
其实就是调用了消息的回调,跑起来了
如果消息里没有绑定Callback,就调用Handler自身的Callback(比如初始化Handler时构造函数中传入的Callback)。handleMessage(msg)函数是空的,给Handler的子类来实现的,匿名内部类重写的也是这个方法。
二、内存泄漏
在我们像下面这样声明Handler时:
package com.meituan.huangdanyang.practise;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler(){
@Override
public void handleMessage(Message message){
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TextView textView = findViewById(R.id.textView);
Log.i("测试","新分支");
handler.sendMessageDelayed(Message.obtain(),100000);
}
}
编译器会给出黄色,警告信息为:
警告里说得很清楚了,因为这个Handler是作为一个内部类被声明的,它可能阻止外部类被gc回收掉。如果这个Handler使用的是主Looper以外的Looper,就没有这个问题,否则,你需要修改你的声明。
之前已经介绍了Handler的基本机制,那我们知道,如果使用handler post了一个delay的消息到了MessageQueue中,在消息被处理前,不会被释放,于是就形成了一个MessageQueue->Message->Handler->Activity这样一个引用链,导致Activity无法释放。
将上面的代码运行之后,用LeakCanary检测内存泄漏,结果发现确实如此:
所以,用匿名内部类的方式声明Handler,确实容易造成内存泄漏。在有后台线程处理网络请求的时候,它没完成,就会一直持有Handler的引用。如果在退出Activity的同时关掉后台线程,那么就相当于释放了Handler的引用,就可以避免内存泄漏。如果Handler是被delay的Message持有了引用,那么使用相应的Handler的removeCallbacks()方法,把消息对象从消息队列移除就行了。
那么如何声明一个安全的Handler呢?按照提示,我们可以声明一个静态内部类的Handler,因为静态内部类不会持有外部类的引用。于是我们自己写一个继承自Handler的静态内部类:
package com.meituan.huangdanyang.practise;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Handler handler = new MyHandler();
public static class MyHandler extends Handler{
@Override
public void handleMessage(Message message){
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TextView textView = findViewById(R.id.textView);
Log.i("测试","新分支");
handler.sendMessageDelayed(Message.obtain(),100000);
}
}
这样确实没有内存泄漏了,可我们也没办法操作Activity里的view了或修改其他非静态变量了。
所以我们可以给静态内部handler类传入一个Activity的弱引用:
package com.meituan.huangdanyang.practise;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
public TextView textView;
private Handler handler = new MyHandler(new WeakReference(this));
public static class MyHandler extends Handler{
private WeakReference appCompatActivity;
public MyHandler(WeakReference appCompatActivity){
this.appCompatActivity = appCompatActivity;
}
@Override
public void handleMessage(Message message){
if(appCompatActivity.get()!=null){
appCompatActivity.get().textView.setText("lalala");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
handler.sendMessageDelayed(Message.obtain(),10000);
}
public void test(){
Log.i("测试","Handler");
}
}
这样既不会内存泄漏,又可以操纵MainActivity了