Android中的Handler是一个用于处理消息和线程间通信的机制。它可以将Runnable对象或Message对象发送到特定的线程中进行处理。
使用Handler的主要目的是在不同的线程之间进行通信,特别是在后台线程中执行一些任务后,将结果发送到UI线程进行更新。
可以用来进行线程的切换,常用于接收子线程发送的数据并在主线程中更新UI。
流程图:
下面是一个示例代码,演示如何创建Message对象并发送给Handler:
// 创建一个Handler对象
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 在UI线程中处理接收到的消息
switch (msg.what) {
case 1:
// 处理消息类型为1的情况
String messageText = (String) msg.obj;
// 执行相应的操作
break;
case 2:
// 处理消息类型为2的情况
// 执行相应的操作
break;
// 可以根据需要处理其他消息类型
}
}
};
// 在其他线程中创建并发送Message对象
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 创建一个Message对象
Message message = handler.obtainMessage();
// 设置消息类型
message.what = 1;
// 设置消息内容
message.obj = "Hello, Handler!";
// 发送消息给Handler所关联的线程
handler.sendMessage(message);
}
});
// 启动线程
thread.start();
Handler源码分析
第一条主线:入队(谁入的队?怎么入的?入的什么队?)
首先进入handler.sendMessage(msg);
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
再点进来sendMessageDelayed(msg, 0);
/**
* Enqueue a message into the message queue after all pending messages
* before (current time + delayMillis). You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
再进来sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis)
public boolean sendMessageAtTime(@NonNull 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);
}
进入enqueueMessage(queue, msg, uptimeMillis)
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
queue.enqueueMessage(msg, uptimeMillis)其实执行的是Message的enqueueMessage方法
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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进入标记
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;
}
说明了入队的过程是:Handler.sendMessage()->sendMessageDelayed()->sendMessageAtTime()->enqueueMessage()->MessageQueue类的enqueueMessage()
Handler发送消息(message)进行入队(MessageQueue)
入队时,如果队列中没有数据,直接将msg放到头部;如果有,则需要遍历队列中的数据,进入插入操作;
第二条主线出队(消费)
app启动的时候会调用ActivityThread这个类
会调用ActivityThread类中的main方法
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// 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();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
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");
}
点进去看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.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
me.mInLoop = true;
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);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;
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;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
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);
}
}
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();
}
}
在for循环中有Message msg = queue.next();在MessageQueue的queue.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 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;
}
}
MessageQueue中for循环取对象,将对象找到返回,此时Looper方法里的msg 就是返回的对象。
并利用msg去调用loop()方法中的dispatchMessage方法
msg.target.dispatchMessage(msg);
说明了第二条主线的流程是:ActivityThread类的main()->looper.loop()->queue.next()
通过next()找到msg对象,然后通过msg绑定target,也就是handler,调用dispatchMessage回调handleMessage方法
/**
* 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);
}
}
第三条主线:Handler,MessageQueue,Message,Looper四个类是什么关系,怎么串联?
- 在mHandler.obtainMessage()中Handler创建Message对象
- 在MessageQueue中的enqueueMessage方法中Handler将创建的对象放入MessageQueue中
- Looper是通过ActivityThread的main()方法进行创建,MessageQueue在创建Looper的时会同时创建
ActivityThread类中
Looper.prepareMainLooper();
prepareMainLooper()点进来
@Deprecated
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(false);
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));
}
sThreadLocal.set方法中创建了Looper对象
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在创建Looper对象的同时,构造方法里也创建了MessageQueue对象
- 在Handler的enqueueMessage方法中,通过msg.target=this将Handler赋值给msg.target对象
而我们在调用mHandler.obtainMessage()中
Message msg= mHandler.obtainMessage();
点进去obtainMessage
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
@NonNull
public final Message obtainMessage()
{
return Message.obtain(this);
}
进来 Message.obtain(this)
/**
* Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
* @param h Handler to assign to the returned Message object's <em>target</em> member.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
进行obtain()方法
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
可以看到在Message.obtain()中message对象采用了复用池,避免资源的浪费;
常见问题解答?如果有错误欢迎指正!
1. 为什么Message需要使用复用机制?每次直接new一个不好么?
当我需要主线程和子线程直接进行沟通的时候一般都使用handler,发送Message对象一般都比较多,如果每发送一次就创建一次的话,会造成资源的浪费,在每次创建Message对象时,都需要分配内存和进行垃圾回收。而使用复用池可以避免频繁地创建和销毁Message对象,从而减少内存的分配和垃圾回收的开销。
Message:单链表结果,链表是非线性,非顺序的物理结构,由N个节点组成;
2. message为什么使用单链表?为啥不使用其他类型:arrayList
- arrayList每次创建的时候会创建一个默认大小的空间,如果超过默认大小的空间就需要进行扩容,就需要对这个ArrayList的内存空间重新进行计算和排列,这可能会导致频繁的内存拷贝和垃圾回收。
- 由于arrayList需要连续的内存块来存储元素,当我们一个arrayList的内存块不够用的时候,重新去创建一个的话又需要开辟一个内存块,当我们这个内存不够用的时候,我们就会去进行gc操作,而且内存中容易出现内存碎片,如果再存放内存容易奔溃。而单链表只需要分配新的节点,不需要进行大规模的数据迁移,而当我们存放的是一个对象的时候,对内存要求不高,只要有合适的空间都可以存放。
3. 子线程能不能new handler?怎么能在子线程new Handler?
子线程不能直接创建Handler对象,如果需要在子线程new Handler需要调用Looper.prepare()
4 .子线程维护Looper的时候需要注意什么?
注意内存泄露的问题;使用完毕后 记得调用quitSafely的方法
5 .MessageQueue是怎么保证线程安全的
通过synchronized同步关键字来对入队操作进行限定
6 .removeMessage的时候是移除队列中的还是队列外的
remove的时候只能移除队列中的数据
7 .Looper能够prepare两次,为什么?
不能prepare两次,因为Looper在创建过程中就加了约束,如果prepare两次会报错。
8.Handler可以切换线程,如何实现?
切换线程其实就是线程间通信的一种。为了保证主线程不被阻塞,我们常常需要在子线程执行一些耗时任务,执行完毕后通知主线程作出相应的反应,这个过程就是线程间通信。
Linux里有一种进程间通信方式叫消息队列,简单来说当两个进程想要通信时,一个进程将消息放入队列中,另一个进程从这个队列中读取消息,从而实现两个进程的通信。
Handler就是基于这一设计实现的。在Android的多线程中,每个线程都有一个自己的消息队列,线程可以开启一个死循环不断地从队列中读取消息。
当 B 线程要和 A 线程通信时,只需要往 A 的消息队列中发送消息,A 的事件循环就会读取这一消息从而实现线程间通信
9.事件循环和消息队列是怎么实现的?
Android的事件循环和消息队列是通过Looper类来实现的。
Looper.prepare()是一个静态方法。它会构建出一个looper,同时创建一个MessageQueue作为Looper的成员变量。MessageQueue是存放消息的队列
当调用Looper.loop()方法时,会在线程内部开启一个死循环,不断地从MessageQueue中读取消息,这就是事件循环。
每个Handler都与一个Looper绑定,Looper包含MessageQueue
10.那这个Looper被存放到哪里?
Looper是存放线程中的,在Looper.prepare()方法会创建一个Looper,它其实还做了一件事,就是将Looper放入线程的局部变量ThreadLocal中。
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));
}
11.什么是ThreadLocal?
ThreadLocal又称为线程的局部变量。它的最大不同在于,一个ThreadLocal实例在不同的线程中调用get()方法可以取出不同的值。
fun main() {
val threadLocal = ThreadLocal<Int>()
threadLocal.set(100)
Thread {
threadLocal.set(20)
println("子线程1 ${
threadLocal.get()}")
}.start()
Thread {
println("子线程2 ${
threadLocal.get()}")
}.start()
println("主线程: ${
threadLocal.get()}")
}
// 运行结果:
子线程1 20
主线程: 100
子线程2 null
ThreadLocal.set可以将一个实例变成线程的成员变量
// ThreadLocal.java
public void set(T value) {
// ① 获取当前线程对象
Thread t = Thread.currentThread();
// ② 获取线程的成员属性map
ThreadLocalMap map = getMap(t);
// ③ 将value放入map中,如果map为空则创建map
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
就是根据当前线程获取线程的一个 map 对象,然后把 value 放入 map 中,达到将 value 变成线程的成员变量的目的
多个 Theadlocal 将多个变量变成线程的成员变量。于是线程就用 ThreadlLocalMap 来管理,key 就是 threadLocal
//ThreadLocal.java
public T get() {
// ① 获取当前线程对象
Thread t = Thread.currentThread();
// ② 获取线程对象的Map
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
// ③ 获取之前存放的value
return result;
}
}
return setInitialValue();
}
和 set 方法差不多,区别就是一个将 value 写入 map,一个从 map 中读取 value
12.为什么要将ThreadLocal作为Looper的设置和获取工具呢?
因为 Looper 要放在线程中的,每个线程只需要一个事件循环,只需要一个 Looper。事件循环是个死循环,多余的事件循环毫无意义。ThreadLocal.set 可以将 Looper 设置为线程的成员变量
同时为了方便在不同线程中获取到 Looper,Android 提供了一个静态对象 Looper.sThreadLocal。这样在线程内部调用 sThreadLocal.get 就可以获取线程对应的 Looper 对象
13.Looper是一个死循环,如果消息队列中没有消息了,这个死循环会一直“空转”吗?
不会,如果事件循环中没有消息要处理但仍然循环,相当于无意义的浪费CPU资源。
在MessageQueue中,有两个native方法,nativePollOnce和nativeWake。
nativePollOnce表示进行一次轮询,来查找是否有可以处理的消息,如果没有就阻塞线程,让出CPU资源。
nativeWake表示唤醒线程
// MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
···
if (needWake) {
nativeWake(mPtr);
}
···
}
在MessageQueue类中,enqueueMessage方法用来将消息入队,如果此时线程是阻塞的,调用nativeWake唤醒线程。
// MessageQueue.java
Message next() {
···
nativePollOnce(ptr, nextPollTimeoutMillis);
···
}
next()方法用来取出消息,取之前调用nativePollOnce()查询是否有可以处理的消息,如果没有则阻塞线程。等待消息入队时唤醒。
14.Looper是个死循环,为什么不会导致ANR呢?
ANR是应用在特定时间内无法响应一个事件时抛出的异常。
典型的例子就是在主线程中执行耗时任务。当一个触摸事件来临时,主线程忙于处理耗时任务而无法在5s内响应触摸事件,此时就会抛出ANR。
但Looper死循环是事件循环的基石,本身时Android用来处理一个个事件的。正常情况下,触摸事件会加入到这个循环中被处理。但如果前一个事件太过耗时,下一个事件等待时间太长超出特定时间,这时才会产生ANR。所以Looper死循环并不是产生ANR的原因。
15.消息队列中的消息是如何进行排序的?
这就要看MessageQueue的enqueueMessage方法了。
enqueueMessage是消息的入队方法。Handler在进行线程间通信时,会调用sendMessage将消息发送到接收消息的线程的消息队列中,消息队列调用enqueueMessage将消息入队。
// MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
// ① when是消息入队的时间
msg.when = when;
// ② mMessages是链表的头指针,p是哨兵指针
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
// ③ 遍历链表,比较when找到插入位置
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// ④ 将msg插入到链表中
msg.next = p;
prev.next = msg;
}
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
消息入队分为3步:
1.将入队的时间绑定在when属性上
2.遍历链表,通过比较when找到插入位置
3.将msg插入到链表中
16.假设我有一个消息,想让它优先执行,如何提高它的优先级呢?
最容易想到的就是修改Message的when属性。但Android为我们提供了更科学简单的方式,异步消息和同步屏障。
在Android的消息机制中,消息分为同步消息,异步消息和同步屏障三种。(同步屏障是target属性为null的特殊消息)。通常我们调用sendMessage方法发送的是同步消息。异步消息需要和同步屏障配合使用,来提升消息的优先级。
同步屏障是一种特殊的消息,当事件循环检测到同步屏障时,之后的行为不再像之前那样根据when的值一个个取消息,而是遍历整个消息队列,查到异步消息取出并执行。
这个特殊的消息在消息队列中像一个标志,事件循环探测到它时就改变原来的行为,转而去查找异步消息。表现上看起来像一个屏障一样拦住了同步消息。所以形象地称为同步屏障。
//MessageQueue.java
Message next() {
···
// ① target为null表明是同步屏障
if (msg != null && msg.target == null) {
// ② 取出异步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
···
}
17.假如我插入了一个同步屏障,不移除,会发生什么事?
同步屏障是用来“拦住”同步消息,处理异步消息的。如果同步屏障不移除,消息队列里的异步消息会一个一个被取出处理,直到异步消息被取完。如果此时队列中没有异步消息了,则线程会阻塞,队列中的同步消息永远不会执行。所以同步屏障要及时移除。
18.同步屏障有哪些应用场景
同步屏障的核心作用是提高消息优先级,保证Message被优先处理 。Android为了避免卡顿,应用在了View绘制中。
19.为什么使用Handler会有内存泄露问题呢?该如何解决?
内存泄露归根到底是生命周期“错位”导致的:一个对象本来应该在一个短的生命周期中被回收,结果被一个长的生命周期的对象引用,导致无法回收。Handler的内存泄露其实是内部类持有外部类引用导致的。形成方式有两种:
1.匿名内部类持有外部类引用
class Activity {
var a = 10
fun postRunnable() {
Handler(Looper.getMainLooper()).post(object : Runnable {
override fun run() {
this@Activity.a = 20
}
})
}
}
Handler 在发送消息时,message.target 属性就是 handler 本身。message 被发送到消息队列中,被线程持有,线程是一个无比“长”生命周期的对象,导致 activity 无法被及时回收从而引起内存泄漏。
解决办法是在 activity destory 时及时移除 runnable
2.非静态内部类持有外部类引用
//非静态内部类
protected class AppHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
}
}
}
解决方法是用静态内部类,并将外部引用改为弱引用
private static class AppHandler extends Handler {
//弱引用,在垃圾回收时,被回收
WeakReference<Activity> activity;
AppHandler(Activity activity){
this.activity = new WeakReference<Activity>(activity);
}
public void handleMessage(Message message){
switch (message.what){
}
}
}
20.HandlerThread和IdleHandler用来干什么的?
HandlerThread 顾名思义就是 Handler+Thread 的结合体,它本质上是一个 Thread。
我们知道,子线程是需要我们通过 Looper.prepare()和 Looper.loop()手动开启事件循环的。HandlerThread 其实就帮我们做了这件事,它是一个实现了事件循环的线程。我们可以在这个线程中做一些 IO 耗时操作。
IdleHandler 虽然叫 Handler,其实和同步屏障一样是一种特殊的”消息"。不同于 Message,它是一个接口
public static interface IdleHandler{
boolean queueIdle();
}
Idle 是空闲的意思。与同步屏障不同,同步屏障是提高异步消息的优先级使其优先执行,IdleHandler 是事件循环出现空闲的时候来执行。
这里的“空闲”主要指两种情况
(1)消息队列为空
(2)消息队列不为空但全部是延时消息,也就是 msg.when > now
利用这一特性,我们可以将一些不重要的初始化操作放在 IdleHandler 中执行,以此加快 app 启动速度
21.能请你聊一下android的handler机制吗?
handler机制是android运行系统的基础,它采用生产者,消费者模式进行设计。其中生产者是handler,handler会生成消息message投递到线程共享的messageQueue有序链表里,再由线程共享Looper取出消息进行消费,将message消息dispatch到对应的handler进行处理。
22.Handler源码分析
在Handler源码中我分为三条主线,第一条主线就是入队的过程,首先源码中是handler.sendMessage(),sendMessageDelayed,sendMessageAtTIme(),equeueMessage(),再到MessageQueue里的equeueMessage方法。
也就是说我们在handler发送message消息进行MessageQueue入队。
入队的过程中没有数据的话,直接将msg放到头部,如果有,则需要遍历队列中的数据,进行插入操作
第二条主线就是出队消费的过程,在app启动的时候会调用ActivityThread类的main()方法,接着调用里面的looper.loop(),再到queue.next(),通过next()找到msg对象,然后msg绑定target,也就是handler,再调用dispatchMessage回调handlerMessage()方法
第三条主线:Handler,MessageQueue,Message,Looper四个类的关系
首先在调用handler.obstainMessage()创建一个message对象。
在MessageQueue中的enqueueMessage方法中Handler将创建的对象放入MessageQueue中。
Looper是用过ActivityThread的main()方法进行创建,MessageQueue在创建Looper的时候会同时创建