Looper简介
Looper.loop是一个死循环,拿不到需要处理的Message就会阻塞,那在UI线程中为什么不会导致ANR?
首先我们来看造成ANR的原因:
1.当前的事件没有机会得到处理(即主线程正在处理前一个事件,没有及时的完成或者looper被某种原因阻塞住了)
2.当前的事件正在处理,但没有及时完成
我们再来看一下APP的入口ActivityThread的main方法:
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
显而易见的,如果main方法中没有looper进行死循环,那么主线程一运行完毕就会退出,会导致直接崩溃,还玩什么!
现在我们知道了消息循环的必要性,那为什么这个死循环不会造成ANR异常呢?
我们知道Android 的是由事件驱动的,looper.loop() 不断地接收事件、处理事件,每一个点击触摸或者说Activity的生命周期都是运行在 Looper的控制之下,如果它停止了,应用也就停止了。只能是某一个消息或者说对消息的处理阻塞了 Looper.loop(),而不是 Looper.loop() 阻塞它,这也就是我们为什么不能在UI线程中处理耗时操作的原因。
主线程Looper从消息队列读取消息,当读完所有消息时,主线程阻塞。子线程往消息队列发送消息,唤醒主线程,主线程被唤醒只是为了读取消息,当消息读取完毕,再次睡眠。因此loop的循环并不会对CPU性能有过多的消耗。
Looper类注释
/**
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.
*
* Most interaction with a message loop is through the
* {@link Handler} class.
*
*
This is a typical example of the implementation of a Looper thread,
* using the separation of {@link #prepare} and {@link #loop} to create an
* initial Handler to communicate with the Looper.
*
*
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare();
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop();
* }
* }
*/
Looper成员变量
public final class Looper {
private static final String TAG = "Looper";
// 静态常量,保证一个线程只有一个 Looper;
// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
static final ThreadLocal sThreadLocal = new ThreadLocal();
@UnsupportedAppUsage
private static Looper sMainLooper; // guarded by Looper.class
private static Observer sObserver;
/**
* 消息队列是在Looper里面创建的
*/
@UnsupportedAppUsage
final MessageQueue mQueue;
/**
* 当前线程
*/
final Thread mThread;
/**
* 打印日志的
*/
@UnsupportedAppUsage
private Printer mLogging;
private long mTraceTag;
/**
* If set, the looper will show a warning log if a message dispatch takes longer than this.
* 如果设置该设置,如果消息分发时间超过此时间,则该循环程序将显示警告日志。
*/
private long mSlowDispatchThresholdMs;
/**
* If set, the looper will show a warning log if a message delivery (actual delivery time -
* post time) takes longer than this.
* 如果设置该设置,如果消息传递(实际传递时间-post时间)花费的时间超过此时间,则循环器将显示警告日志。
*/
private long mSlowDeliveryThresholdMs;
....
}
Looper构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); // 消息队列 这样就实现了Looper和MessageQueue的关联
mThread = Thread.currentThread(); // 当前线程 这样就实现了Thread和Looper的关联
}
Looper.prepare();
/**
* Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//每个线程只允许执行一次该方法,第二次执行的线程的TLS已有数据,则会抛出异常。
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建Looper对象,并且保存到当前线程的TLS区域。
sThreadLocal.set(new Looper(quitAllowed));
}
初始化当前线程和Looper,这样可以在实际开始启动循环(loop())之前创建一个Handler并且关联一个looper。确保在先调用这个方法,然后调用loop()方法,并且通过调用quit()结束。
这里面的入参boolean表示Looper是否允许退出,true就表示允许退出,对于false则表示Looper不允许退出。
prepareMainLooper()方法
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
// 设置不允许退出的Looper
prepare(false);
synchronized (Looper.class) {
//将当前的Looper保存为Looper。每个线程只允许执行一次
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
初始化当前当前线程的looper。并且标记为一个程序的主Looper。由Android环境来创建应用程序的主Looper。因此这个方法不能由咱们来调用。另请参阅prepare()
- 首先 通过方法我们看到调用了prepare(false);注意这里的入参是false
- 其次 做了sMainLooper的非空判断,如果是有值的,直接抛异常,因为这个sMainLooper必须是空,因为主线程有且只能调用一次prepareMainLooper(),如果sMainLooper有值,怎说说明prepareMainLooper()已经被调用了,而sMainLooper的赋值是由myLooper来执行,
- 最后调用myLooper()方法来给sMainLooper进行赋值。
myLooper()方法
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里的sThreadLocal.get()是和prepare(boolean)方法里面的sThreadLocal.set(new Looper(quitAllowed));一一对应的。而在prepareMainLooper()方法里面。
提出一个问题,在prepareMainLooper里面调用myLooper(),那么myLooper()方法的返回有没有可能为null?
答:第一步就是调用prepare(false);,所以说myLooper()这个方法的返回值是一定有值的。
Looper.loop();
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
// 获取TLS存储的Looper对象
final Looper me = myLooper();
//没有Looper 对象,直接抛异常
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取当前Looper对应的消息队列
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();
// 进入 loop的主循环方法
// 一个死循环,不停的处理消息队列中的消息,消息的获取是通过MessageQueue的next()方法实现
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
// 默认为null,可通过setMessageLogging()方法来指定输出,用于debug功能
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 用于分发消息,调用Message的target变量(也就是Handler了)的dispatchMessage方法来处理消息
msg.target.dispatchMessage(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.
// 确保分发过程中identity不会损坏
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
// 打印identiy改变的log,在分发消息过程中是不希望身份被改变
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);
}
// 将Message放入消息池
msg.recycleUnchecked();
}
}
loop进入循环模式,不断重复下面的操作,直到没有消息时退出循环
读取MessageQueue的下一条Message
把Message分发给相应的target
再把分发后的Message回到消息池,以便重复利用
Looper的退出循环方法
/**
* Quits the looper.
*
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
*
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
*
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
*
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
退出循环
将终止(loop()方法)而不处理消息队列中的任何更多消息。在调用quit()后,任何尝试去发送消息都是失败的。例如Handler.sendMessage(Message)方法将返回false。因为循环终止之后一些message可能会被无法传递,所以这个方法是不安全的。可以考虑使用quitSafely()方法来确保所有的工作有序地完成。
/**
* Quits the looper safely.
*
* Causes the {@link #loop} method to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* However pending delayed messages with due times in the future will not be
* delivered before the loop terminates.
*
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
*
*/
public void quitSafely() {
mQueue.quit(true);
}
安全退出循环
调用quitSafely()方法会使循环结束,只要消息队列中已经被传递的所有消息都将被处理。然而,在循环结束之前,将来不会提交处理延迟消息。
调用退出后,所有尝试去发送消息都将失败。就像调用Handler.sendMessage(Message)将返回false。
MessageQueue.mQueue.quit(boolean safe);
void quit(boolean safe) {
//当mQuitAllowed为false,表示不运行退出,强行调用quit()会超出异常
//mQuitAllowed 是在Looper构造函数里面构造MessageQueue()以参数参进去的
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
// 防止多次执行退出操作
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
//移除尚未触发的所有消息
removeAllFutureMessagesLocked();
} else {
//移除所有消息
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
//mQuitting=false,那么认定mPtr!=0
nativeWake(mPtr);
}
}
当safe=true,只移除尚未触发的所有消息,对于正在触发的消息并不移除
当safe=false,移除所有消息