Android源码剖析:基于-Handler、Looper-实现拦截全局崩溃

本文详细剖析了Android中HandlerThread、MessageQueue的源码,解释了Handler如何实现消息处理,包括MessageQueue的next()方法的阻塞机制以及enqueueMessage()的执行顺序。通过理解这些核心组件,有助于处理崩溃和ANR问题,提升应用稳定性。
摘要由CSDN通过智能技术生成

button.setOnClickListener {
handler?.post {
println(Thread.currentThread())
}
handler?.post {
println(Thread.currentThread())
}
}

输出结果:

System.out: Thread[Thread-2,5,main]
System.out: Thread[Thread-2,5,main]

HandlerThread

HandlerThread 是 Android 对Thread的封装,增加了Handler的支持,实现就是实现了前面例子的功能

val handlerThread = HandlerThread(“test”)
handlerThread.start()
handler = Handler(handlerThread.looper)

MessageQueue 源码剖析

我们都知道Handler的功能非常丰富,拥有立刻执行post()、延迟执行postDelayed()、定时执行postAtTime()等执行方式。下面就从源码分析是如何实现的。

public final class MessageQueue {
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值