前言
基于Android SDK 28。
使用方式
使用方式不必多说(仔细看看自己还是不是第一种LowB写法):
//编译器已经明确提示这样写存在内存泄露
@SuppressLint("HandlerLeak")
private Handler mHandlerOld = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
//推荐写法
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
return false;
}
});
Handle源码分析
首先是Handle构造方法(以上面调用的构造方法为例):
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) { //private static final boolean FIND_POTENTIAL_LEAKS = false;
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(); //拿当前线程的Looper构建消息循环系统
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;
}
首先FIND_POTENTIAL_LEAKS是一个布尔常量,好像这个if判断就是个多余的代码块,不管它,继续往下看。
然后就是拿当前的线程的Looper,如果当前线程的Looper为空,就提示可能是没有调用Looper.prepare()。
//获取当前线程的Looper
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这个ThreadLocal是一个抽象泛型类,就是用作线程隔离的,它可以在不同线程存储数据并且不同线程具有不同的数据副本。那么就可以肯定Looper.prepare()就存数据了:
/**
*Initialize the current thread as a looper.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//一个线程只能存在一个Looper
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
//quitAllowed表示是否运行退出
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
所以,new Handler之前必须要先初始化Looper,所以在子线程中实例Handler时:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare(); //必须要初始化Looper
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
}
}).start();
那么为什么我们可以在Activity里可以直接使用Handler呢?那是因为在ActivityThread的mian方法里面已经初始化Looper了:
//ActivityThread.java
public static void main(String[] args) {
//....
Looper.prepareMainLooper();
//...
Looper.loop(); //开启循环,后面会分析
}
/**
* Looper.java
* 应用程序主线程的Looper,在Android环境构建时就应该创建了
* 所以无需自己调用,而且也不能在主线程调用Looper.prepare()
*/
public static void prepareMainLooper() {
prepare(false); //传入flase表示主线程循环队列是不允许中断退出的
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Handler 发送消息的两种方式
第一种是post(Runnable)、postDelayed()等等:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
可以看到是调用的sendMessageDelayed方法,其实就是发送消息的第二种方式了,这里其实最关键的是在于getPostMessage()这个方法:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
其实就是把传入的runnable参数存入Message对象的callback成员变量。
第二种是sendMessage、sendMessageDelayed、sendEmptyMessage等等:
其内部都是调用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);
}
//将消息放入消息队列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //处理该消息的目标就是当前Handler
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
当然,三种释义是有区别的,sendMessage就是表示消息立即需要处理,而sendMessageDelayed用于发送相对于当前时间多久后需要处理的消息,sendMessageAtTime用于发送在指定的绝对时间上需要处理的消息。
Handler 处理消息
发现事情并不简单。
Handler 总结
- 创建Handler时会将当前线程中的Looper和MessageQueue关联到其成员变量中,起到连接的作用
Message 源码分析
public final class Message implements Parcelable {
public int what; //标示消息的唯一性
/**
* 传递的数据低成本替代品,如果要传递其他类型的数据或者多个数据,可以使用Bundle
*/
public int arg1;
public int arg2;
/*package*/ long when; //指定消息执行时间,如果为0表示立即执行
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next; //以单链表形式存储
public static final Object sPoolSync = new Object(); //实例化空的一个静态对象作消息的锁
private static Message sPool; //消息池
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
}
虽然Message有一个公有的构造方法,但是还是推荐使用Message.obtain()实例化一个Message:
/**
* 从全局消息池中返回一个消息实例
* 这样在大多数情况下能避免重新分配对象
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
该方法就是如果消息池有消息就取出消息池的头部返回,并把当前消息池头部指向下一条消息,然后消息池大小减一,如果消息池为空,就实例化一个消息并返回。
那么消息池是在哪赋值的呢?其实是在recycle()方法里:
/**
* 当一个消息正在使用时,是不能回收的
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
/**
* 将废弃的消息投入消息池中重新利用,避免重新创建对象的开销
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool; //消息池头部的下一条消息指向为空
sPool = this; //把当前消息作为消息池头部
sPoolSize++;
}
}
}
可以看到,消息池是不可能为空的,里面缓存的都是空的Message对象。只需要调用recycle方法便可以把废弃消息放入消息池以便重新利用,放入消息池中的消息已经被清空所有数据,因此不能被立即使用,就需要调用obtain方法返回消息对象后重新初始化。
MessageQueue
消息队列。
在上面Handler.sendMessageAtTime时,就会调用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; //链表插入操作
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
通过Handler的sendXxx、postXxx方法都会把Message压入MessageQueue中,Message在消息队列中是按照消息执行时间(when)排列的,因此消息入队前对应以下四种处理情况:
- 当 p = null ,即当前消息队列为 null,新加入的消息必然会存入消息队列头部
- 当 when = 0,即需要立即处理,此时应该加入消息队列头部
- 当 when < p.when ,即新加入的消息的处理时间要早于消息队列头部消息的处理时间,仍然需要把新消息加入消息队列头部
- 但不满足以上三种情况时,就需要遍历消息队列,插入合适的位置
将新消息加入消息队列只是enqueueMessage方法的第一步,如果新消息加入到消息队列头部,此时处理消息的线程处于block状态,则需要调用nativeWake方法唤醒消息处理线程。
Looper 源码分析
前面我们说在主线程是不需要调用Looper.prepare()方法即可使用Handler,那是因为在ActivityThread中的main方法中已经调用了Looper.prepareMainLooper(),这个方法我们已经分析过了,我们在分析随后调用的Looper.loop()方法。
在分析此方法之前,可以看到在Looper的源代码之前有注释:
* This is a typical example of the implementation of a Looper thread,
* using the separation of {@link #prepare} and {@link #loop} to create an
* initial Handler to communicate with the Looper.
* //把一个普通线程变为Looper线程仅需两步
*
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare(); //第一步初始化Looper
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop(); //第二步开启循环
* }
* }
所以,我们在对照ActivityThread,其实就是把主线程变为一个Looper线程,下面看Looper.loop()方法到底做了什么事情:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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;
//...
for (;;) { //无限轮询消息队列取出消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
// 没有消息时,表明消息队列已经停止了,那什么时候主线程的消息队列会退出呢?
// 那只有应用程序退出时,主线程的消息队列才会停止
// 在Android中,一切皆为消息,包括触摸事件、视图绘制、显示、刷新都是消息
// 所以在正常情况下,主线程的消息队列很难没有消息
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);
}
//...
try {
msg.target.dispatchMessage(msg); //mag.target = handler 分发消息
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//...
msg.recycleUnchecked(); //回收消息
}
}
所以Looper.loop方法中做了三件事:
- 调用MessageQueue.next方法取出消息
- 调用Message中的target成员变量分发消息
- 调用Message.recycleUnchecked回收消息
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;
}
}
妈耶,有点懵。
总结
- 使用Handler时推荐在其构造方法中传入一个callback,更要注意如果在子线程中使用,一定要初始化Looper。
- 一个线程只能有一个Looper,Looper是存在于ThreadLocal中,Looper中维护着一个MessageQueue,主线程已经初始化Looper了(Looper.prepareMainLooper()),然后通过Looper.loop轮询消息队列取出消息
- 我们通过Handler的postXxx和sendMessageXxx方法发送消息,其内部都是调用Handler.sendMessageAtTime(Message msg , long uptimeMillis)方法,在该方法内会调用MessageQueue.enqueueMessage(Message msg, long when)把消息放入消息队列,根据when的大小决定把新加入的消息插入到头部还是插入其中,如果新加入的消息被插入头部且该线程已经blocked,还需要唤醒该线程
- 获取一个Message推荐使用Message.obtain()方法获取,Message中维护一个消息池,里面缓存的都是空的Message对象。只需要调用recycle方法便可以把废弃消息放入消息池以便重新利用,放入消息池中的消息已经被清空所有数据,因此不能被立即使用,就需要调用obtain方法返回消息对象后重新初始化。
- 调用MessageQueue.next()方法可能会阻塞,即使消息队列中没有消息了,Looper也不会退出而是等待。当消息队列中没有消息时,表明消息队列已经停止了,这种情况只能是应用程序退出了。
后记
其实还有一些东西没分析到,特别是MessageQueue,涉及的Native方法太多了。Mark下!