上篇文章我们从源码角度分析了如何在主线程、子线程创建Handler对象。可参考:Handler异步消息传递机制(三)在主线程、子线程中创建Handler,源码(Android 9.0)彻底解析
那么创建Handler之后,如何发送消息呢?这个流程相信大家也已经非常熟悉了,我们继续以文章 Handler异步消息传递机制(一)Handler常用实现方式 的demo为例,然后进行源码跟踪解析!
下面是 Handler对象:在新启动的子线程发送消息 的代码:
public class DownLoadAppFile {
public void download(String urlPath, Handler handler, ProgressBar pb) {
try {
//下载apk的代码,这里用线程睡眠模拟
Thread.currentThread().sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = Message.obtain();
msg.what =1;//成功
//msg.what =2;//失败
handler.sendMessage(msg);//发送消息
}
}
Handler到底是把Message发送到哪里去了呢?为什么之后又可以在Handler的handleMessage()方法中重新得到这条Message呢?接下来我们来看一下发送消息的源码:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
它里面调用了sendMessageDelayed方法,
往下追踪
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
我们可以看到sendMessageDelayed方法,其中msg参数就是我们发送的Message对象,而delayMillis参数则表示延迟发送消息的时间(毫秒),这里默认传入的为0
往下追踪
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);
}
我们可以看到sendMessageAtTime()方法同样接收两个参数,其中msg参数就是我们发送的Message对象,而uptimeMillis参数则表示发送消息的时间,SystemClock.uptimeMillis() + delayMillis 即它的值等于自系统开机到当前时间的毫秒数再加上延迟时间。
然后对 MessageQueue对象queue进行了赋值,这个MessageQueue又是什么东西呢?学过java基础的可能会马上想到Queue,基本上一个队列就是一个先入先出(FIFO)的数据结构。同样在这里MessageQueue 直译过来就是 消息队列 的意思,用于将所有收到的消息以队列的形式进行排列,并提供入队和出队的方法。
那么enqueueMessage()方法就是入队的方法了,我们来看下这个方法的源码:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target赋值为this,也就是把当前所在类handler,作为msg的target属性。然后将这三个参数都传递到MessageQueue的enqueueMessage()方法中,也就是说handler发出的消息,最终会保存到消息队列中去。
调用sendMessage方法其实最后是调用了类MessageQueueen消息队列的queueMessage入队方法。
那么有了MessageQueueen消息队列的queueMessage入队方法。它必然有相对应的出队方法。
Handler对象在新启动的子线程发送消息以后,接下来在主线程中,Handler类处理消息的方法handleMessage被自动回调。
那么接下来在主线程中,回调handleMessage方法的流程是怎样的呢?
Android的主线程就是ActivityThread,主线程的入口方法为main,我们继续来看一下ActivityThread类中main方法的源代码:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("");
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
第47行调用了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.");
}
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;
}
// 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);
}
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
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();
}
}
我们可以看到前面几行代码,首先对Looper、MessageQueue对象进行了赋值,然后第23行进入了一个死循环for( ; ; ){ },然后不断地调用的MessageQueue的next()方法,Message msg = queue.next() 很明显这个next()方法就是消息队列的出队方法。
接下来你会发现第57行执行了msg.target.dispatchMessage(msg); 其中msg.target就是指的Handler对象,你回看一下上面enqueueMessage()方法就可以看出来。接下来当然就要看一看Handler中dispatchMessage()方法的源码了,如下:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在第8行进行判断,如果mCallback不为空,则调用mCallback的handleMessage()方法,否则直接调用Handler的handleMessage方法,并将消息对象作为参数传递过去。这样我相信大家就都明白了为什么handleMessage()方法中可以获取到之前发送的消息了吧!