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;
}
// 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);
}
try {
msg.target.dispatchMessage(msg);
} finally {}
if (logging != null) {
logging.println(”<<<<< Finished to " + msg.target + " " + msg.callback);
}
msg.recycleUnchecked();
}
}
public void quit() {
mQueue.quit(false);
}
}
如果主线程发生了异常,就会退出循环,意味着APP崩溃,所以我们我们需要进行try-catch,避免APP退出,我们可以在主线程再启动一个 Looper.loop()
去执行主线程任务,然后try-catch这个Looper.loop()方法,就不会退出。
基于 Handler 实现单线程的线程池
从上面的 Looper.loop()
,我们可以利用 Handler 实现单线程池功能,而且这个线程池和主线程一样拥有立刻执行post()
、延迟执行postDelayed()
、定时执行postAtTime()
等强大功能。
// 错误用法
var handler: Handler? = null
Thread({
handler = Handler()
}).start()
当我们在异步线程执行上面的代码,就会报错 Can't create ha