// handler 构造函数, 包含两个重要的成员变量mLooper和mQueue(MessageQueue内部采用链表实现)// 创建新的Handler时, 如果没有提供Looper对象, 则使用当前创建线程中的Looper对象
public Handler(@Nullable Callback callback, boolean async){
mLooper = Looper.myLooper();if(mLooper == null){
throw new RuntimeException("Can't create handler inside thread "+ Thread.currentThread()+" that has not called Looper.prepare()");}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;}
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async){
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;}
public final boolean sendMessage(@NonNull Message msg){returnsendMessageDelayed(msg,0);}
public final boolean sendMessageDelayed(@NonNull Message msg,long delayMillis){if(delayMillis <0){
delayMillis =0;}returnsendMessageAtTime(msg, SystemClock.uptimeMillis()+ delayMillis);}// 将消息放入MessageQueue handler发送消息函数最终都是调用sendMessageAtTime函数
public boolean sendMessageAtTime(Message msg,long uptimeMillis){
MessageQueue queue = mQueue;if(queue == null){
RuntimeException e = new RuntimeException(
this +" sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);return false;}returnenqueueMessage(queue, msg, uptimeMillis);}
private boolean enqueueMessage(MessageQueue queue, Message msg,long uptimeMillis){// 把 handler 赋值给msg.target
msg.target = this;if(mAsynchronous){
msg.setAsynchronous(true);}// 加入mQueue队列,检测是否需要唤醒mLooperreturn queue.enqueueMessage(msg, uptimeMillis);}
3 Handler 处理消息
// Looper
public staticvoidprepare(){prepare(true);}
private staticvoidprepare(boolean quitAllowed){if(sThreadLocal.get()!= null){
throw new RuntimeException("Only one Looper may be created per thread");}//创建Loop对象 & 每个线程只能创建唯一的Looper对象
sThreadLocal.set(new Looper(quitAllowed));}// 创建主线程Looper对象
public staticvoidprepareMainLooper(){prepare(false);
synchronized (Looper.class){if(sMainLooper != null){
throw new IllegalStateException("The main Looper has already been prepared.");}
sMainLooper =myLooper();}}
public staticvoidloop(){// 获取当前线程的Looper对象
final Looper me =myLooper();if(me == null){
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}
final MessageQueue queue = me.mQueue;for(;;){// 从MessageQueue中读取Message,没有消息则休眠
Message msg = queue.next();// target == Handler 调用Handler的dispatchMessage函数
msg.target.dispatchMessage(msg);// 将对应的msg对象加入到缓存池
msg.recycleUnchecked();}}//处理消息
public voiddispatchMessage(Message msg){// 1 通过post提交的消息最终由Handler的handleCallback函数处理if(msg.callback != null){handleCallback(msg);}else{// 2 Callback函数不为空,则调用Callback的handleMessageif(mCallback != null){if(mCallback.handleMessage(msg)){return;}}// 3 以上都没有处理,则交给Hanlder的handleMessage处理handleMessage(msg);}}