Handler消息机制相关类介绍
- Message:是在线程之间传递的消息,它可以在内部携带少量的消息,用于在不同线程之间交换数据。
- Handler:处理者的意思,它主要是用于发送和处理消息。发送消息一般使用Handler的sendMessage()方法,接收消息使用Handler的handleMessage()方法。
- MessageQueue:消息队列的意思,它主要用于存放所有通过Handler发送的消息,每个线程中只会有一个MessageQueue对象。
- Looper:是每个线程的MessageQueue管家,调用Looper的Loop方法,就会进入到一个无限循环当中,然后每当发现MessageQueue中存在一条消息,就会将它取出并传递到Handler的handleMessage()方法中,每一个线程也只会有一个Looper对象。
- ThreadLocal:是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。线程本地变量,存放Looper对象。每个线程对应自己的Looper。
Message的生成
- new Message()
- Message.obtain()
- Handler.obtain()
Handler 类
Handler handler = new Handler() { // 匿名子类对象(),调用父类默认的构造函数
public void handleMessage(Message msg) {
// 更新UI操作
}
}
// Handler类的默认构造函数
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
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());
}
}
// Looper 的静态方法myLooper(),获取到本线程的Looper对象,如果是在主线程中,则设置Looper对象是在ActivityThread类的main()方法中设置。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 获取MessageQueue对象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
ActivityThread 类中的main方法如下:
public static final void main(String[] args) {
...
//Looper对象的初始化,放到线程本地变量中
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler();
}
....
//轮询器轮询取消息
Looper.loop();
....
}
}
Looper 类
// 创建线程本地变量,存放Looper对象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
// 初始化主线程的Looper对象
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
// 只能初始化一次,否则会报异常
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
// 参数quitAllowed false:不允许中断;true:允许中断
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
// 把Looper对象保存到ThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
// Looper的构造方法
private Looper(boolean quitAllowed) {
// 创建MessageQueue对象,并设置是否可以中断
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
// 调用此方法创建Looper,是可以中断的
public static void prepare() {
prepare(true);
}
Handler 发送消息
// 1、handler对象 sendMessage()
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
// 2、
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
// SystemClock.uptimeMillis() 获取系统的时间,从开机时间算起
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
// 3、
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
// 获取MessageQueue对象
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);
}
// 4、
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
// this 就是当前Handler对象,把Handler对象给msg对象的target属性
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
// 消息队列按照消息的进入顺序和发送时间排序,唤醒looper轮询器
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue 插入消息
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;
// 如果消息为空,或者获取当前消息的时间为0,或者当前消息的时间比消息队列的第一个消息的时间小,则把当前消息插入到消息队列的头部
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;
}
}
// 插入消息,Message是一个单链表形式,要找到插入消息的前一个位置和后一个位置
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 轮询器取消息
public static void loop() {
// 获取当前的Looper对象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 获取MessageQueue对象
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 1、msg.target对象就是前面设置的handler对象
msg.target.dispatchMessage(msg);
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);
}
// 2、消息回收利用
msg.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.
// 如果当前时间,小于msg的时间,则等待并计算等待时间
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;
}
// 把取出的消息的next设置为null,取消与下一个节点的关联
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 dispatchMessage()处理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 如果设置了消息的callback,则处理callback
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// 走handleMessage方法处理消息
handleMessage(msg);
}
}
// 回调callback的run方法
private static void handleCallback(Message message) {
message.callback.run();
}
// handler的handleMessage空方法,让子类去实现,处理业务逻辑
public void handleMessage(Message msg) {
}
Message 消息回收
// 消息回收方法
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
// 消除message消息对象里的属性值
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) { // 就是Object对象满足synchronized语法
if (sPoolSize < MAX_POOL_SIZE) { // MAX_POOL_SIZE=50
next = sPool; // 设置新的回收消息的下一个为sPool
sPool = this; // 设置该消息为新的消息头
sPoolSize++; // 回收的消息+1
}
}
}
Handler消息机制流程图
在子线程中使用Handler机制
* 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(); // 开启Looper轮询器,读取消息,没有消息则等待
* }
* }