1.Handler,Looper原理
图解:
其根本点在于:
2. HandlerThread
HandlerThread继承自 Thread,唯一的特殊就是:
正常Thread中是没有 Looper在运行的,而HandlerThread的run方法执行后,就会给自己的 Thread准备一个looper,
并使 looper.loop() 循环起来;
所以使用 HandlerThread 创建的线程作为 Handler所在线程时,不需要再单独准备Looper;
但创建 Handler时,需要确保使用的 HandlerThread已经执行过 handlerThread.start();
只有 start调用完成 run()函数后才能准备好 Looper:
补充下,这个函数里使用 synchronized(this)的原因是为了在 Looper准备好之后,通知想要使用 Looper的 Handler所在线程,因为Handler 是在 HandlerThread之外的其他线程创建的,所以调用 HandlerThread.getLooper()时,可能HandlerThread还没有执行完成 run函数,也即还没准备好 Looper,所以会wait直到Looper准备好:
在这个函数里可以看到,如果 Looper还没有准备好,则会wait(),直到 Looper准备好;
还有一点,函数开始时,就判断当前Thread是否 isAlive(),如果没有 alive,则返回 null,导致 Handler创建失败,而只有Thread.start 之后,Thread才会 alive,所以,这是为什么使用 HandlerThread Looper创建 Handler之前,需要先通过HandlerThread.start() 使 Thread 运行起来的原因。
同样,HandlerThread退出时,也需要调用 quit()函数来结束 Looper 在当前 HandlerThread的执行: