---笔记文,非专业文章,如有表述模糊的请参阅其他大神文章或源码,有错误多谢指正
Handler是Android消息机制的上层接口,开发过程中开发者只需要和Handler交互即可。 Handler对Android开发者来说主要作用是更新UI,实际上这只是对Handler的一种特殊场景应用。本质上Handler主要完成切换线程操作。
一、为什么在子线程不能更新UI
在View的
requestLayout
过程中会调用
ViewRootImpl 的 checkThread 方法
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
在ViewRootImpl创建过程中 mThread = Thread.currentThread(),也就是说如果我们在子线程thread1中创建一个View,那么此View也只能在thread1中被修改。一般被创建的View都在UI线程中被创建。如果在子线程中更新UI,上述checkThread()会抛出异常引起程序崩溃。
为什么Android系统会使用checkThread来禁止子线程访问UI?UI控件不是线程安全的,并发访问会导致UI控件处于不可预知的状态,而UI上锁会降低UI访问效率。
二、ThreadLocal
ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定的线程中可以获取到存储的数据。Looper的作用域就是当前线程,因此使用THreadLocal存取Looper非常合适。按照以上对ThreadLocal的作用描述,一个全局HashMap也可以实现类似功能,为什么系统没采用呢?
1.安全性,一个全局hashmap可以在已知线程描述的情况下在任意线程使用其他线程作为key取出hashmap中的looper,显然这不符合looper的作用域,难以保证其安全性。
2.复用性,如果使用hashmap系统需要给looper提供一个LooperManager,同理ActivityThread和AMS同样应用到了ThreadLocal,也就需要对应的Manager。
3.弱引用,ThreadLocal内部封装了value的弱引用,在value需要被销毁时无需考虑ThreadLocal处的内存泄漏。
三、MessageQueue
Message mMessages;//单链表数据结构队列
入队方法:
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;
//如果当前列表为空或when = 0 或 when先于队首message执行,message插入队首
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.唤醒native
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
next是一个无限循环方法,当消息队列中没有消息时,next方法会一直阻塞,直到新消息入队,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;
// 此处会判断是否有同步屏障,同步屏障会让next忽略同步消息优先处理异步消息
// 我们常用的 handler = new Handler(),用此handler发送的消息实际上就是同步消息
// 如果有需求使用同步屏障一定要谨慎处理
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.
// 下一条消息没到时间 - 设置超时时间唤醒native
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 {
//是否保存idle 取决于器queueIdle方法
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; }
}
四 Looper:
Looper 会不停地从MessageQueue中查询是否有新消息,如果有就立即处理,否则阻塞。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
构造方法为私有,我们无法使用构造方法创建一个looper
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));
}
其构造方法在prepare方法中被使用,在prepare new一个Looper对象之外还会把对象放在ThreadLocal中。
创建好Looper之后还需要调用Looper的loop方法让Looper开始工作。
五。Handler
handler作为Android消息机制的应用层API,主要包含发送和接收过程。消息的放可以通过post和send一系列方法实现,这些方法的最终都是通过sendMessageAtTime方法将消息放入MessageQueue。
Handler 发送消息的过程是往消息队列里插入一条消息。Looper的循环过程中会通过MessageQueue的next方法将消息返回给looper,looper处理之后会调用Handler的dispatchMessage方法进入handler的消息处理阶段。
Handler会优先检测message的callback是否为空,如果不为空就通过handleCallback来处理消息。Message的callback就是一个Runnable对象
private static void handleCallback(Message message) {
message.callback.run();
}
六、IdleHandler
idleHandler并不属于Handler类,它是MessageQueue内定义的一个接口,内部包含一个queueIdle方法,并通过MessageQueue对象的addIdleHandler方法将实现idleHandler的实例传入MessageQuee的mIdleHandlers列表中。反观MessageQueue的next方法我们可以得出,IdleHandler对象只会在MessageQueue消息队列没有内容需要处理的时候才会被执行,并且会根据queueIdle根方法的返回值决定是否继续保留此IdleHandler对象,如果返回true则其会被保留并在next方法下次没有需要处理的消息的时候执行。
public static interface IdleHandler {
boolean queueIdle();
}
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
七、主线程的消息循环
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");
}
Android的主线程是ActivityThread.在主线程的入口方法main中会调用
Looper.prepareMainLooper();
,通过此方法创建主线程的Looper和MessageQueue。在main方法的最后通过Looper.loop()
来开启主线程的消息循环,自此Activity的main方法进入死循环,任何需要运行在主线程的内容都需要通过ActivityThread中的Handler--ActivityThread.H来执行。