欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler机制之Looper源码解析

程序员文章站 2022-07-14 15:06:00
...

Looper类

为一个线程执行循环取出Message的类。

异步线程和Handler与Looper的使用案例

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
         //开始创建Message队列
         Looper.prepare();
          mHandler = new Handler() {
             public void handleMessage(Message msg) {
                 //处理传递过来的Message
             }
          };
         //会循环调度MessageQueue中message
         Looper.loop();
     }

Looper类源码分析

从构造器和属性开始分析:

   //ThreadLocal 线程局部变量,会为每一个线程都创建副本。
   static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
   //主线程的looper
   private static Looper sMainLooper; 
   //当前运行线程上的Message队列
    final MessageQueue mQueue;
    //当前运行的线程
    final Thread mThread;
    
    //构造器 ,quitAllowed:该线程的Message队列是否允许退出。
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        //获取当前运行的线程
        mThread = Thread.currentThread();
    }

来看下Looper.prepare():开始创建线程的Looper和MessageQueue

    public static void prepare() {
        prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
        //当前线程的局部Looper已经存在
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //将Looper存到当前线程的ThreadLocal变量中
        sThreadLocal.set(new Looper(quitAllowed));
    }

接下来,看Looper.loop():

public static void loop() {
        //获取到当前线程的Looper
        final Looper me = myLooper();
        if (me == null) {
            //调用Looper.loop()方法之前,必须调用prepare(),否则会抛异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;
        //确保线程的标示identity是本地进程的标示
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        //一直循环
        for (;;) {
            //MessageQueue.next()会阻塞,则会进行等待状态
            Message msg = queue.next(); 
            if (msg == null) {
                //当Message队列中没有message,该队列已经停止,跳出for循环
                return;
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
               //调用message中目标Handler的dispatchMessage()
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            msg.recycleUnchecked();
        }
    }

从上可知: loop()方法的逻辑包含:开始执行线程message队列,会将message传递Handler.dispatchMessage()

接下来,看一下有关于主线程的looper的相关方法:

    public static void prepareMainLooper() {
        //主线程的Message队列不允许退出,设置为false.
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    /**
     * 返回程序主线程的Looper.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

实际上开发中,只需要调用getMainLooper()可以获取到主线程的Looper.
然而prepareMainLooper()又是在哪里调用的呢?

经过查找源码,发现ActivityThrad类中的main()方法:

 public static void main(String[] args) {
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        Looper.loop();
    }

从上可知:程序进程一创建,就开始初始过主线程的Looper,且开始循环调用主线程中Message。

最后,再来了解一下如何停止一个带有消息队列的线程:

    public void quit() {
        mQueue.quit(false);
    }
    //android 高版本中调用
    public void quitSafely() {
        mQueue.quit(true);
    }

Looper的停止调度,会调用MessageQueue的停止方法,会让MessageQueue中的Message返回为空,最终导致跳出在Looper.loop()中的for循环。