Handler+Looper+MessageQueue+Message机制机制
作用:作用:
跨线程通信,异步通信。当子线程中进行耗时操作后需要更新UI时,通过Handler将有关的UI操作切换到主线程中执行。
四要素:四要素:
Message(消息):需要被传递的消息,其中包含了消息标识(what),消息处理数据和处理对象(arg1,arg2,obj),发送该消
息的Handler对象(target)等,由MessageQueue统一列队,最终由Handler处理。
MessageQueue(消息队列):由Looper负责管理,管理Handler发送过来的Message,其底层实现采用的是单链表。
Handler(处理者):负责Message的发送及处理。通过 Handler.sendMessage() 方法把消息发送给Looper管理的
MessageQueue并通过Handler.handleMessage()方法处理Looper分给它的消息。
Looper(消息循环器):每个线程只有一个Looper,负责管理MessageQueue,通过Looper.loop()会不断地从
MessageQueue中取出消息(Message),并将消息分给对应的目标处理者(Handler)处理。
消息只能在某个具体的Looper上消耗,因此每个Handler都会绑定一个Looper,但是多个Handler可以绑定同一个Looper(这
也是在主线程中能够创建新的Handler的原因)。
源码分析源码分析
每个线程只有一个Looper对象,主线程的Looper对象由Android系统调用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() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Looper里面有个静态对象sThreadLocal维护着所有线程对应的Looper对象
// sThreadLocal.get() will return null unless you've called prepare().