我们知道,不论时我们还是系统,在进行线程间通信都会用到handler,也就是消息机制。
一般情况下耗时操作放在子线程里,更新UI放在主线程里,一旦子线程完成耗时操作,就要回到主线程去更新UI了,这时就要用到Handler了。
- Handler:消息的控制器
- Message:消息的载体
- MessageQueue:存放消息
- Looper:控制消息队列的循环
简单展示一下Handler的用法
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText("success");
}
};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv_handler);
new Thread(new Runnable() {
@Override
public void run() {
//模拟耗时操作
SystemClock.sleep(3000);
handler.sendMessage(new Message());
}
}).start();
}
可以看到我们在子线程发送消息,然后Handler接收消息进行操作,接下来我们来看看一下他的源码。
首先跟踪到sendMessage,可以看到无论是sendMessage还是sendEmptyMessage,最后都会进入到sendMessageDelayed。只不过sendEmptyMessage需要传一个what的值,具体是调用obtain方法获取一个message,将what值赋值给它
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
为什么不new一个message呢,我们来看看obtain(),是怎么做的?
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();
}
发现原来已经定义好了一个massage池,如果了解数据结构的话,能看出来这是一个链表结构,我们直接从里面取就可以
接着继续看sendMessageDelayed()
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
这里校正了一下时间,继续看sendMessageAtTime
public boolean sendMessageAtTime(@NonNull 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);
}
这里判断一下messageQueue是否为空,不为空就一切正常,然后把消息放入消息队列中,继续看enqueueMessage()是如何插入消息的
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
先将msg的目标指向自己,然后设置为同步消息,这样由于同步屏障的机制,UI绘制也会更流畅,接着入队
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;
}
这也是一个链表结构。首先会对链表头指针做判断,如果为空,那么就把当前消息插入到链表头部,如果链表不为空,那么比较一下当前消息的执行时间,若时间小于头指针所存储的消息,那么也要将他插入到链表头部。若以上条件都不满足,那么就要对链表进行一个遍历,找到适当的位置并插入。
Looper
looper负责取出消息交给handler,它是怎么工作的?
public static void prepare() {
prepare(true);
}
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));
}
一个线程只能有一个looper,然后它new looper传递给sThreadLocal.set()中,看看这个方法:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
这里是创建了一个表,key是当前线程,value是这个新建的looper
再看看Looper的构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
总体上好像就是把线程,looper,queue三者对应起来了,接下来looper准备好后就是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.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
me.mInLoop = true;
// 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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
// 要判断一下线程是否切换了
me.mSlowDeliveryDetected = false;
for (;;) {
if (!loopOnce(me, ident, thresholdOverride)) {
return;
}
}
}
这里显示判断了一下looper是否为空,然后应该是对该线程进行校验,然后开始死循环直到loopOnce()返回false,那我们看看什么时候返回false
private static boolean loopOnce(final Looper me,
final long ident, final int thresholdOverride) {
Message msg = me.mQueue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return false;
}
// ......
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
// ......
msg.recycleUnchecked();
return true;
}
这段代码好长,基本上就是检查线程是否切换,性能分析相关的东西。精简一下就是这个样子,msg.target上面说到就是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就是我们例子中的覆盖的那个方法,它其实是一个空方法,要我们去做逻辑处理
到这里就分析完了,总结一下:
- handler与messageQueue与looper与线程是多对一对一对一的关系。
- message中主要的成员变量有target(目标Handler),obj(Object类型的数据),data(Bundle类型的数据),what(message的id),flag(同步或是异步消息)
- 创建Message对象尽量用obtain()方法,这样是从一个消息池中不断的取出消息来使用,避免过多的内存分配
- 主线程在一开始创建时就已经创建并开启了Looper,所以我们在主线程中使用Handler时就已经和主线程、消息队列有了联系,就不用再手动调用loop()了。而在子线程,我们需要先looper.prepare(),把looper和该线程保存起来,然后再loop()取出
- 文章开头流程:在子线程中,借用主线程的handler发送一条消息,此时还在子线程中,只不过发送的消息会放在主线程的looper循环执行