1.简介
Handler主要用于线程间通信,且可以传送数据。是一种消息传递机制。
2.作用
在多线程的应用场景中,将子线程中获取的耗时结果传递到 UI主线程,从而实现 子线程对UI的更新处理,最终实现异步消息的处理。且也可以实现子线程之间的数据传递,但是要添加Looper对象。
3.常用对象
Handler 线程间通信的一种机制,同时也可以传送数据。
Looper 轮询机制,不断获取队列里的消息,让handler目标去处理消息
MessageQueue 消息队列,保存msg消息的。
Message 数据的载体。
4.使用方式
1.第一种
public Handler() {
this(null, false);
}
2.第二种
public Handler(Callback callback) {
this(callback, false);
}
5 Handler源码分析
我们从平时的使用流程来分析handler是如何通信和传输数据。
5.1 Handler.java
//发送消息
handler.sendMessage(msg)
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
默认发送延迟为0的事件
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
// SystemClock.uptimeMillis() 自启动后的毫秒数
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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) {
//发送的目标对象 就是当前的handler对象
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
// 队列处理消息msg
return queue.enqueueMessage(msg, uptimeMillis);
}
5.2 MessageQueue
进入MessageQueue 对象,找到方法enqueueMessage
//when 什么时间发送,默认当前立即发送
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) { //目标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;
//队列里的msg对象
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;
// 无限循环,把msg 放进队列里,这个队列是个链表结构的
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;
}
6 Looper源码分析
把消息放入队列后,接下来该Looper对象上场,looper对象主要是轮询消息,轮询就是获取队列的每个消息,然后交给Handler目标对象分发消息。
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;
...省略
boolean slowDeliveryDetected = false;
// 无限循环 获取队列里的msg,然后由目标对象分发消息,target==Handler对象
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);
}
....
try {
// 目标对象分发消息,去接收处理
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
。。。。。。。。。省略
}
}
/**
* Handle system messages here.
* callback 不为null 就执行callback的run方法
*
*/
public void dispatchMessage(Message msg) {
// callback 不为null 就执行callback的run方法
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg); //分发消息,也就是我们最终去重写的方法
}
}
/** 分发消息,也就是我们最终去重写的方法
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
Looper 是轮询机制,作用是不断从消息队列获取message,然后有handler发送。
当我们创建子线程的时候,要给Thread 添加Looper对象,否则无法发送消息。
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
使用Looper之前要去调用prepare方法,它主要创建了Looper对象后,被绑定给ThreadLocal对象。同时再创建之前还对threadLocal里是否包含Looper对象进行了判断,注意异常的描述,一个thread只能有一个Looper。
Looper的构造,做了两个事,创建一个消息队列,获取当前的线程对象。到此所有环境都准备好了,接下来就可以获取消息进行处理了。
代码有点长,首先获取looper ,拿到消息队列MessageQueue,然后开启一个死循环,无限从队列里拿消息,如果消息为null,再进行下次循环,去拿消息,反反复复,无穷匮也。如果拿到了消息,开始分发消息,target 就是handler,再往下看
/**
* 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;
// 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);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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);
}
msg.recycleUnchecked();
}
}
/** 如果没有callback对象,就会调用handleMessage方法,这不是就是咱们创建
* 重写的方法嘛,至此,整个大体流程就结束了。其实在这里,大家也能看出创建handler
* 的时候,有Callback对象的创建,优先级较高。
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}