Looper.prepare方法创建关联的looper,调用Looper.loop方法处理消息,直到loop停止。大部分与消息循环的交互是通过Handler
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实例 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); final MessageQueue mQueue;#关联的消息队列 final Thread mThread; #创建Looper的线程 public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { #prepare只允许调用一次 throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); #新实例创建,存入本地线程变量副本 } private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); #消息队列实例化 mThread = Thread.currentThread(); #创建的线程 }
Looper.prepareMainLooper方法,内部prepare传参为false,表示不允许退出。
public static @Nullable Looper myLooper() { return sThreadLocal.get(); } public static void loop() { final Looper me = myLooper(); if (me == null) { #没有调用prepare方法,线程本地变量获取不到looper实例,直接抛出异常 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; .... boolean slowDeliveryDetected = false; for (;;) { #从MessageQueue取消息, Message msg = queue.next(); // might block if (msg == null) { // 没有消息,消息队列正在退出 return; } try { #调用handler.dispathMessage方法传递消息 msg.target.dispatchMessage(msg); ... } catch (Exception exception) { ... throw exception; } finally { ... } #回收到回收池内 msg.recycleUnchecked(); } }
Looper主要通过loop方法从MessageQueue中循环获取消息,然后交给Handler处理。
在线程中要先使用Looper.prepare方法创建Looper,再调用Looper.loop方法获取和处理消息。
本文为Adamin90原创文章,转载无需和我联系,但请注明来自http://www.lixiaopeng.top