> 文档中心 > 一文搞懂Handler机制

一文搞懂Handler机制


什么是Handler?

Handler是进程内部、线程间的一种通信机制。

Handler、Looper、MessageQueen、Message的关系

Message: 消息对象
MessageQueen: 存储消息对象的队列
Looper:负责循环读取MessageQueen中的消息,读到消息之后就把消息交给Handler去处理。
Handler:发送消息和处理消息
这里写图片描述

源码解析

要想使用handler ,首先要保证当前所在线程存在Looper对象
主线程不需要主动创建Looper对象是因为主线程已经为你准备好了,详见android.app.ActivityThread->Looper.prepareMainLooper()
我们创建的子线程如果想用handler接收数据,需要先通过Looper.prepare()创建Looper

 Looper.prepare(); ...//创建Handler并传入 Looper.loop()

Looper类

Looper构造方法

private Looper(boolean quitAllowed) {   mQueue = new MessageQueue(quitAllowed);   mThread = Thread.currentThread();}

创建Looper对象的时候,同时创建了MessageQueue,并让Looper绑定当前线程。但我们从来不直接调用构造方法获取Looper对象,而是使用Looper的prepare()方法
prepare()使用ThreadLocal 保存当前Looper对象,ThreadLocal 类可以对数据进行线程隔离,保证了在当前线程只能获取当前线程的Looper对象,同时prepare()保证当前线程有且只有一个Looper对象,间接保证了一个线程只有一个MessageQueue对象

Looper的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)); }

Looper开启循环

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;   Binder.clearCallingIdentity();   final long ident = Binder.clearCallingIdentity();   for (;;) {Message msg = queue.next(); // might block 也许会堵塞,一会在next方法中解析if (msg == null) {    return;}try {    msg.target.dispatchMessage(msg);} finally {    if (traceTag != 0) { Trace.traceEnd(traceTag);    }}msg.recycleUnchecked();   }}

Lopper通过loop()开启无限循环,通过MessageQueue的next()获取message对象。一旦获取就调用msg.target.dispatchMEssage(msg)将msg交给handler对象处理(msg.target是handler对象),最后回收

Handler类

Hanlder实例化

 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对象,以便于将消息加入MessageQueue

发送消息

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;    if (mAsynchronous) { msg.setAsynchronous(true);    }    return queue.enqueueMessage(msg, uptimeMillis);  }

enqueueMessage中首先为msg.target赋值为this,this对象就是Handler,为发送消息出队列交给handler处理埋下伏笔。

处理消息

 public void dispatchMessage(Message msg) {     if (msg.callback != null) {  handleCallback(msg);     } else {  if (mCallback != null) {      if (mCallback.handleMessage(msg)) {   return;      }  }  handleMessage(msg);     }  }

前面我们提到Looper.loop()获取到消息时会调用handler的dispatchMessage方法进行处理,handler处理消息就是调用我们重写的handleMessage()方法,或者我们可以在创建Handler实例时实现Callback接口,一样可以处理从MessageQueue出来的消息

MessageQueue类

MessageQueue 构造方法

 MessageQueue(boolean quitAllowed) { mQuitAllowed = quitAllowed; mPtr = nativeInit();  }

MessageQueue初始化过程同时初始化底层的NativeMessageQueue对象,并且持有NativeMessageQueue的内存地址(long)

MessageQueue的next()

Message next() {    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(); //刷一下,就当是Android系统的一种性能优化操作 } nativePollOnce(ptr, nextPollTimeoutMillis);//native底层实现堵塞,堵塞状态可被新消息唤醒,头一次进来不会延迟 synchronized (this) {     final long now = SystemClock.uptimeMillis();     Message prevMsg = null;     Message msg = mMessages;//获取头节点消息     if (msg != null && msg.target == null) {  do {      prevMsg = msg;      msg = msg.next;  } while (msg != null && !msg.isAsynchronous());     }     if (msg != null) {  if (now < msg.when) {      nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);//获取堵塞时间  } else {      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;   //直接出队列返回给looper  }     } else {  nextPollTimeoutMillis = -1;//队列已无消息,一直堵塞     }     if (mQuitting) {  dispose();  return null;     } pendingIdleHandlerCount = 0; nextPollTimeoutMillis = 0;    }}

虽然looper也开启了循环,但是到了真正干活的时候它却调用了MessageQueue的next(),要想搞明白怎么个堵塞,先看这三个对应的条件
nextPollTimeoutMillis=0 不堵塞
nextPollTimeoutMillis<0 一直堵塞
nextPollTimeoutMillis>0 堵塞对应时长,可被新消息唤醒
next()中,因为消息队列是按照延迟时间排序的,所以先考虑延迟最小的也就是头消息。当头消息为空,说明队列中没有消息了,nextPollTimeoutMIllis就被赋值为-1,当头消息延迟时间大于当前时间,堵塞消息要到延迟时间和当前时间的差值
当消息延迟时间小于等于0,直接返回msg给handler处理
nativePollOnce(ptr, nextPollTimeoutMillis)方法是native底层实现堵塞逻辑,堵塞状态会到时间唤醒,也可被新消息唤醒,一旦唤醒会重新获取头消息,重新评估是否堵塞或者直接返回消息

消息入栈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;}

消息入栈时,首先会判断新消息如果是第一个消息 或者 新消息没有延迟 或者 新消息延迟时间小于队列第一个消息的,都会立刻对这个消息进行处理。只有当消息延迟大于队列头消息时,才会依次遍历消息队列,将消息按延迟时间插入消息队列响应位置。

Message类

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();}

建议使用obtain()获取Message对象,因为Message维护着一个消息池,这个消息池的数据结构是单向链表,优先从池子里拿数据,如果池子里没有再创建对象。如果Message对象已存在,可以使用obtain(msg)方法,最终也会调用obtain()

消息的回收

void recycleUnchecked() {    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对象销毁,而是将Message对象的值恢复初始值然后放回池子,等待使用

因为android会频繁的使用Message的对象,使用“池”这种机制可以减少创建对象开辟内存的时间,更加高效的利用内存,因此"池"这种机制被应用于频繁大量使用的类对象的情况,我们常说的“线程池”也是基于同样的原理。

这里写图片描述
总结: 要想在当前线程使用handler机制,首先确保当前线程存在Looper

Looper.parper()创建一个 当前线程的Looper对象,同时创建一个MessageQueue对象

每个线程只有一个Looper对象和一个MessageQueue对象

Looper.loop()开始循环,没有msg情况下进入堵塞状态(-1)

Message对象最好通过Message.obtain()获得

Handler发送消息进入队列,如果没有延迟唤醒堵塞 Looper获得msg ,调用msg.targe.dispachMessage处理消息

关闭Activity如果栈中有未出栈的message,需清除handler.removeMessage(int)

子线程不再使用handler时,要调用loop.quit(),loop.quitSafely()

虽然表面上看是looper循环队列,并将msg给handler,但实际上是MessageQueue的next()去完成的,MessageQueue同时还承担消息的入队列,并对消息按照延迟时间从小到大进行了排序。鉴于MessageQueue如此大的工作量,在Android 2.3版本后,MessageQueue中next()方法的堵塞机制转移到了native层去处理,也就是我们使用的nativePollOnce(ptr, nextPollTimeoutMillis)方法

本篇博文没有分析屏障逻辑(msg.target==null),以及底层的堵塞逻辑,也没有分析异步消息逻辑(msg.isAsynchronous()==true)