Handler消息机制
Android中的消息机制主要指的就是Handler运行机制,Handler是Android消息机制的上层接口,我们一般只需要和handler打交道就行。Handler的运行机制很简单,同过与MessageQueue和Looper配合就可以很方便的把一个任务切换到handler所在的线程中去。
1.Handler存在的意义?
Android由于开发规范的规定是不能在子线程中进行UI相关的操作的。
如果在子线程访问了UI会触发异常,ViewRootImpl中checkThread进行了线程检查。源码如下
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
为了主线程中也就是UI线程界面渲染交互流畅一般是不允许在主线程进行一些耗时操作,否则容易触发ANR异常。还有Android的UI控件不是线程安全的,多线程访问可能会让界面处在一种不可控的状态。但是在开发中我们进行网络数据请求,I/O等耗时操作放在子线程,然后需要修改界面,这时候如果没有一个方法可以把任务切换线程那我们将无法实现一系列的页面更新操作。因此Android系统提供Handler这个解决方案。
2.消息机制流程
Handler创建后会使用当前线程的Looper构建起消息循环系统,Handler发送消息给MessageQueue,MessageQueue调用enqueueMessagge方法将消息加入队列,Looper发现有新消息进来后就会处理消息。将会调用Handler的dispatchMessage方法交给handler。由于Looper是运行在Handler创建线程上。所以消息就成功切换到了Handler所在线程。这就是消息机制的简单流程。可以参考下面这位大神做的流程图。接下来对MessageQueue,Looper进行具体分析。
图片来自https://www.jianshu.com/p/9e4d1fab0f36
3.MessageQueue消息队列的工作原理
MessageQueue中主要操作就是插入和删除消息。对应enqueueMessage,和next方法
虽然MessageQueue我们叫他消息队列但是它本身的数据结构是个单链表。这种数据格式在插入删除上更具有优势。我们先看下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;
}
主要实现的就是单链表的插入。
我们再看下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.
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;
}
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;
}
}
我们看到next方法是一个无限循环的方法,当队列里面没有消息的时候就会阻塞在这里。有消息就会把消息返回并且从单链表中移除。
4.Looper的工作原理
(1)Looper的创建
Looper在消息机制中起着消息循环的作用。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。我们在源码prepare方法下面还看到另一个prepareMainLooper方法
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
这是一个创建主线程Looper的方法,但是上面注释写的很清楚,它是由Android环境创建的,不需要我们主动去使用,我们看下调用这个方法的地方,是在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("<pre-initialized>");
//在这里调用
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");
}
ActivityThread就是主线程,所以我们可以在主线程中直接使用Handler而不需要自己初始化Looper就是这个原因。
这里我们也可以得出,handler不是仅仅只能把消息切换到主线程,只要我们想要在有数据回调的线程使用Looper.perpare()去创建一个Looper,然后创建handler,最后 Looper.loop()开启循环可以啦,如下代码,这样我们就能把其他线程的消息切换到“test”线程啦。
new Thread("test"){
@Override
public void run() {
//创建Looper
Looper.prepare();
//Handler与Looper建立关系
Handler handler = new Handler();
//开启循环
Looper.loop();
}
};
(2)Looper的循环开启
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;
// 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是一个死循环,不断的地调用MessageQuery的next去获取消息。唯一退出的循环的方式就是queue.next()返回null,Looper的quit或者quitSafely会调用MessageQueue的quit或quitSafely
Looper的quit和quitSafely
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
MessageQueue的quit
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
这里通过native 设置 mPtr的值,在Message的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;
}
我们继续回到Looper的loop。如果next返回值就会调用 msg.target.dispatchMessage(msg);去处理消息这里msg.target就是发送消息的handler。最终handler发送的消息就回到了自己的dispatchMessage方法。这里的dispatchMessage是在创建handler时候的Looper执行的,所以就成功的切换了线程。
小疑问?
这里大家可能有个疑问,Looper.perpare()开启无限循环以后这里为什么不会阻塞主线程呢?
这里面其实涉及到Linux pipe/epoll机制。具体可以参考https://www.wanandroid.com/wenda/show/8685
(3)Handler工作原理
先看一下Handler的构造方法,前四个为可以使用的,后三个带boolean参数的为@hide方法
总共有6个构造方法,只是其中的参数有差异。
- CallBack参数
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
我们使用handler的时候一般都是通过派生Handler子类去重写handleMessage去实现 ,直接使用Callback去创建就可以不用派生子类。
- Looper
使用一个指定的Looper去构造,不使用的话都会使用主线程中默认的Looper - boolean async
无法直接从构造方法中赋值,默认为false。发送的消息是否是异步
post相关方法
Handler发送消息会调用post相关方法,post方法最终会调用send相关方法。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
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);
}
send方法最后会调用enqueueMessage,调用MessageQueue的enqueueMessage方法,在消息队列中插入一条消息。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//注意这里 msg.target进行赋值,就是当前的Handler
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
dispatchMessage
上面分析Looper时候知道,Looper在取到消息后就会调用 msg.target.dispatchMessage(msg);这里的msg.target就是发送消息的Handler。
/**
* 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);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
首先检查msg.callback是否为null,不为null就调用message.callback.run()的方法。然后在判断mCallback是不是为null,不为null就回调Callback的handleMessage。没有设置Callback就正常调用handleMessage方法。
小结
Handler的消息机制就简单介绍到这里。Handler的消息机制不仅仅只是用于在主线程更新UI,它是一种同一进程中线程沟通的手段。在主线程ActivityThread启动后,还有启用一个Handler与消息队列进行交互。这个就是ActivityThread.H。ActivityThread.H定义了一系列的消息,包括启动Activity,调用Activity的各个生命周期。ActivityThread通过ActivityThread.H与ApplicationThread等各个系统线程进行通讯。共同构建起了Android消息机制。