Handler机制相信很多人在面试Android岗的时候都会被问到相关的问题,虽然已经有很多人整理了,但我还是想自己整理一下,权当是给自己的加深自己对于handler机制的理解。
首先我们先了解下关于Handler的四个主要组成部分:Handler、Looper、Messagequeue、Message
来看Handler的构造方法:
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback) {
this(callback, false);
}
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
/**
* @hide
*/
@UnsupportedAppUsage
public Handler(boolean async) {
this(null, async);
}
/**
* @hide
*/
public Handler(@Nullable 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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
/**
* @hide
*/
@UnsupportedAppUsage
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
当我们调用handler构造方法,都会走到最后的两个使用@hide注解的方法,我们可以看到,初始化了mLooper 和 mQueue。当我们没有构造方法中传Looper,会通过 Looper.myLooper() 方法来当前线程绑定的Looper,从这个方法一层层的往下找。
Looper#myLooper
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
ThreadLocal#get
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
可以看到该方法通过ThreadLocal来拿到当前线程绑定的Looper。那么 ThreadLocal在哪里和Looper绑定线程呢?
Looper#prepare
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));
}
ThreadLocal#set
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
可以看到,通过调用 Looper.prepare 方法,通过ThreadLocal将当前线程和Looper绑定起来。
然后调用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;
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
//关键方法--------
msg.target.dispatchMessage(msg);
//关键方法---------
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
}
}
MessageQueue#next
@UnsupportedAppUsage
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 (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);
}
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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
我简化了一些,关键代码标识出来了,在Looper中通过调用queue.next方法获取message,而在MessageQueue.next中也是通过死循环遍历msg.next,保证了当前的handler不会退出。在获死循环取到msg,调用 msg.target.dispatchMessage(msg)方法,Message中的target就是我们当前线程绑定的handler
@UnsupportedAppUsage
/*package*/ Handler target;
所以相当于调用了Handler#dispatchMessage(msg):
/**
* Handle system messages here.
*/
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看到,回调了handlerMessage方法,到这里是不是很熟悉了,我们来看看我们经常使用handler的方法
val mHandler = object : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when(msg.what){
//根据消息去做想要的事
}
}
}
这样,我们发送的消息就通过该回调方法被我们获取到了。
总结:
Handler 中声明了 一个 Looper 和 ThreadLocal ,Looper中又实例化了一个MessageQueue,在Handler的构造方法中,调用了Looper.myLooper()来获取线程绑定的Looper,所以在实例化Handler前需要通过调用Looper.prepare() 方法来创建 Looper,并且该方法通过 ThreadLocal 将Looper与当前线程绑定。Looper.loop()方法则会开始不断尝试从 MessageQueue 中获取 Message, 并执行msg.target.dispatchMessage(msg) ,msg.target 就是发送该消息的 Handler,Handler的dispatchMessage(msg)方法中回调了handleMessage(msg),这样就能在Handler中的handleMessage(msg)中处理接收到的msg。
但是光知道这个还不够,还会有以下问题:
问题一、为什么Looper死循环没能造成UI线程卡死?
我们来看ActivityThread#main方法
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
AndroidOs.install();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("");
Looper.prepareMainLooper();
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"));
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看到loop方法在main方法的最后,loop之后就是抛异常了。之所以死循环,可以保证UI线程不会被退出,因为Android中界面绘制都是通过Handler消息来实现,这样可以让界面保持可绘制的状态。真正会卡死主线程的操作是在回调方法onCreate/onStart/onResume等操作时间过长,会导致掉帧,甚至发生ANR,looper.loop本身不会导致应用卡死。
问题二、为什么在主线程使用handler不需要管Looper?
在ActivityThread#main方法中,有调用到 Looper.prepareMainLooper(); 和 Looper.loop(); 两个方法;
Looper#prepareMainLooper:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
可以看到该方法中调用了prepare方法,并且通过myLooper调用到了ThreadLocal.get方法拿到当前主线程的Looper。
问题三、在使用Handler时有没有碰到如下警告?
因为直接使用内部类的方式实例化handler会造成handler持有当前的activity实例,从而导致内存泄漏。通常做法使用静态内部类 或者 单独拎出来,使用弱引用来持有当前的activity。
如下代码:
class MyHandler(activity: ActivityA) : Handler() {
//持有弱引用HandlerActivity,GC回收时会被回收掉.
private val mActivity: WeakReference = WeakReference(activity)
override fun handleMessage(msg: Message) {
val activity = mActivity.get()
super.handleMessage(msg)
if (activity != null) {
//执行业务逻辑
}
}
}
好了,就是以上这些,我要去学习了,我爱学习...