好奇害死猫-思考题:
- ViewRootImpl如何验证UI操作是否来自于UI线程?
- Android系统为什么限制子线程进行UI操作?
- Handler创建时会采用当前线程的Looper来构建内部的消息循环系统,如果当前线程没有Looper会报什么样的错误?如何解决这个问题?
- ThreadLocal的工作原理和使用场景。
Handler简介
Handler是Android消息机制的上层接口;通过Handler可以轻松的将一个任务切换到Handler所在的线程中去执行。具体的使用场景如下:
有时候需要在工作线程执行耗时的I/O操作,操作完成后需要在UI上做出一些响应,
由于安卓开发规范的限制工作线程是不能直接访问UI控件的,
否则就会触发系统异常。这个时候可以通过在主线程中创建的Handler将更新UI的操作切换到主线程中执行。
本质上来说,Handler并不是专门用于更新UI的,他只是常常被开发者用于更新UI。
Handler的运行机制
Android的消息机制主要是指Handler的运行机制。
Handler的运行需要底层MessageQueue和Looper的支撑。
Message:消息对象;
MessageQueue:消息队列。内部存储一组消息,以队列的形式对外提供插入(enqueueMessage)和移除(next)的接口;实质上是采用单链表(插入和删除比较有优势)的结构存储消息列表。
Looper:消息循环对象。Looper会以无限循环的形式去查找是否有新的消息,有则处理,否则就一直处于wait状态。(Looper怎么保证每个线程只存在一个 ThreadLocal的相关概念)
以上的主要的组成单元了解完毕之后,剩下的部分就是详细的了解。Handler是如何有机的将这些整合在一起的。(这里着重源码层面的分析)
Handler核心类的源码分析
构造器部分
从源码来看Handler具有7个构造器,看起来Handler构造器很复杂,其实不然。实际上Hanlder只有两个真正的构造器,其他的5个均为缺省构造器,即通过this方法来调用两个真实的构造器。
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(boolean async) {
this(null, async);
}
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());
}
}
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
如上图所示,五个缺省的构造器,旨在为在不同的应用场景下创建Handler提供快捷构造的方案。根据使用场景可以大致分为两种场景:
- 不需要传入Looper对象的主线程;
- 需要传入Looper对象的工作线程(工作线程中,创建Handler进行线程间通信);
主线程创建时用到的构造器分析
public Handler(Callback callback, boolean async) {
//if 里面的代码旨在检测潜在内存泄漏的代码,默认是关闭状态(FIND_POTENTIAL_LEAKS:false)
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类的静态方法来获取当前的Looper对象,如果获取的对象is null 则会运行时报异常
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;
}
这里需要注意的是Looper类中的静态方法myLooper()的实现细节,因为涉及到了面试中常问的ThreadLocal的工作原理和使用场景,面试中一定要注意。
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
* 大致意思:该方法返回与当前线程相关联的Looper对象,如果当前线程没有关联的Looper对象,则返回null
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
在这个主线程使用的Handler构造器中不需要传入Looper的原因是因为主线程在应用启动的时候已经为我们创建了Looper对象了。这样的一个话的结论未免有些空洞,下面的代码可以说明这一点。
//本方法位于AcitivityThread类中,主线程在这里创建了Looper对象并执行了loop方法
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// 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对象
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
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);
//开启loop进行轮询
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
/**
* 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()}
* 为当前应用的主线程创建Looper对象,主线程中的Looper必须由安卓环境创建,千万不要在自己的代码里面调用。参见: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();
}
}
/** 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) {
//ThreadLocal来将Looper与线程进行关联
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
先上结论,分析下Handler中发送消息的代码发现,几乎所有的发送方法都是直接或者间接的调用setMessageAtTime方法实现。这里有一个例外方法sendMessageAtFrontOfQueue,该方法的目的是进入队列的头部,因此将msg.when设置为0(正常情况下when为系统启动时间的毫秒数+delayMillis),通过该操作实现添加到消息队列的队头,除此之外与setMessageAtTime方法并无差别;因此这里着重分析该方法如何将消息存入MessageQueue中。
[图片上传中。。。(9)]
MessageQueue方法对消息的管理是通过单向链表实现消息队列的管理。进入队列的方法是enqueueMessage(Message msg, long when)。实现细节上,第一种情况为插入队首的情况,如当前队列为null、新插入的Message对象when为0或者小于队首的when属性时。具体代码如下图;第二种情况是遍历队列,插入when小于next.when的位置或者队尾。具体代码如下。
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;
}
至此插入队列的操作介绍完毕。
消息的轮询机制
Looper中的轮询方法
/**
* 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();
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;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
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;
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 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;
}
}
根据轮询(loop)的代码可以发现,一旦messageQueue的next方法返回null,轮询就结束了,如果next方法不堵塞的话,Looper就无法持续的工作。怎么解决这个问题呢。这里就涉及到Linux中的进程间通信的机制-管道(pipe)。原理:在内存中有一个特殊的文件,这个文件有两个句柄(引用),一个是读取句柄,一个是写入句柄。重点就在与mPtr 这个指针。因此MessageQueue的next方法进行堵塞。
消息队列中没有消息则轮询结束,当调用Handler的发送消息的方法进行消息发送时会唤醒Looper进行消息的轮询,具体消息的分发(Handler的CallBack负责)和处理由Handler(handleMessage)来负责。
/**
* 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);
}
}
大致流程介绍完毕。
Handler这里其实还是只讲到了源码层面,不算真正的底层实现。真正的底层实现涉及到的Linux知识,还需要进一步的研读。路漫漫其修远兮,吾将上下而求索。