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

handler源码分析之Looper

程序员文章站 2022-07-14 19:53:49
...

类描述

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线程实现的经典例子,使用prepare和looper方法分开创建一个初始handler来与Looper来通信。

此类包含基于MessageQueue设置和管理事件循环所需的代码。 影响队列状态的API应在MessageQueue或Handler上定义,而不是在Looper本身上定义。 例如,空闲处理程序和同步屏障在队列中定义,而准备线程,循环和退出在循环中定义。

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

如果不调用prepare方法,sThreadLocal.get()方法将返回空,也就是在myLooper()静态方法返回为空,my Looper是在Handler构造时候调用,如果为null,将会抛出异常.

  • prepare() 方法
/** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

在当前线程初始化一个looper,在创建handler时启动looper。确保在调用prepare方法后,调用loop方法,并使用quit方法退出。

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

每个线程只能绑定一个Looper,否则会抛异常。
创建一个新的looper实例,保存在sThreadLocal

  • 构造
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

在创建Looper实例的时候,创建一个Message Queue和当前线程,
也是就Looper绑定了当前线程和一个Message Queue。quitAllowed默认为true。

  • 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();
        }
    }

调用prepare(),quitAllowed参数为false,校验sMainLooper是否已经存在,如果已经存在,会抛异常,最后调用 sMainLooper = myLooper(),到目前为止,还没有体现出来Main这个意思。

看看方法描述怎么将:将当前线程初始化一个Looper,并标记成mainLooper,main Looper是在android应用环境创建的,所以不需要调用这个方法。

还是没看出来,先放这里。

  • getMainLooper()
/**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

返回应用程序的mainLooper,位于应用程序的主线程主。
又是这个sMainLooper。不行了 我必须看看它到底怎么就办成main的。妈的看来不是在looper类中显示出来的。还得先放一放。

  • myLooper()
/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

返回与当前线程相关联的Looper,如果线程未与Looper绑定,返回null。sThreadLocal.get()这玩意一会在搞它。

-myQueue

/**
     * Return the {@link MessageQueue} object associated with the current
     * thread.  This must be called from a thread running a Looper, or a
     * NullPointerException will be thrown.
     */
    public static @NonNull MessageQueue myQueue() {
        return myLooper().mQueue;
    }

这个mQueue就是初始化Looper时绑定的mQueue。必须从Looper的线程调用,否则会出险空指针一场。

  • isCurrentThread
/**
     * Returns true if the current thread is this looper's thread.
     */
    public boolean isCurrentThread() {
        return Thread.currentThread() == mThread;
    }

判断当前的线程是否是looper的线程

  • setMessageLogging
/**
     * Control logging of messages as they are processed by this Looper.  If
     * enabled, a log message will be written to <var>printer</var>
     * at the beginning and ending of each message dispatch, identifying the
     * target Handler and message contents.
     *
     * @param printer A Printer object that will receive log messages, or
     * null to disable message logging.
     */
    public void setMessageLogging(@Nullable Printer printer) {
        mLogging = printer;
    }

控制由这个Looper处理的消息记录,如果启用将在每个消息分派的开始和结束时,将日志消息写入 printer 中,用以识别目标的Handler和Message。

  • quit
/**
     * Quits the looper.
     * <p>
     * Causes the {@link #loop} method to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @see #quitSafely
     */
    public void quit() {
        mQueue.quit(false);
    }

退出Looper 真正的操作是调用 Message Queue中的quit方法。
描述:终止loop方法,不会在处理消息队列(MessageQueue)中其它消息。
在退出Looper之后,任何尝试将Message加入到消息队列都将失败,消息队列不会接受任何消息,handler.sendMessage将返回false。
使用这个方法可能是不安全的,因为有一些消息可能不会在循环终止之前派发。可以使用quitSafely()方法来确保有所的待处理的Handler都以有序的方式完成。

  • quitSafely()
/**
     * Quits the looper safely.
     * <p>
     * Causes the {@link #loop} method to terminate as soon as all remaining messages
     * in the message queue that are already due to be delivered have been handled.
     * However pending delayed messages with due times in the future will not be
     * delivered before the loop terminates.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p>
     */
    public void quitSafely() {
        mQueue.quit(true);
    }

和quit方法比起来就差了一个参数,true表示安全退出,
一旦消息队列的素有消息都处理完毕,就会立即退出loop方法。
但是延迟发送的消息会在looper终止之前传递。
退出looper之后任何,不允许任何Message发送到Message Queue

  • loop()最主要的方法了
/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

上面的一些方法只要知道是干啥的 又是作用就行,最主要的方法就是这个loop方法。
调用loop方法首先去调用myLooper()获取当前线程绑定的Looper,
没有肯定不行,抛异常,之前也都说过,一个线程绑定一个Looper,一个Message Queue(prepare-->new Looper()),然后获取到绑定的Message Queue,接下来是一个死循环,从消息队列中取出Message,这里如果没有消息,线程就会阻塞在这里,如果Message 返回 null,结束方法,如果有Message,继续往下走,
mLogging控制由这个Looper处理的消息记录,如果启用将在每个消息分派的开始和结束时,将日志消息写入 printer 中。最后把Message释放,并放入到回收池中。

总结

Looper类的作用:
Looper绑定一个线程和消息队列(new Looper()体现),loop方法开启死循环,不停的从MessageQueue中获取Message,并把消息根据Target分发出去。使用getMainLooper可以获取到主线程Looper在MainThread#Main中初始化调用。

未知问题解决
  • prepareMainLooper
    prepareMainLooper静态方法,实在ActivityThread#main方法中调用,Looper也是在这里调用的。在app创建的时候开始创建这些东西。
Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

为什么开启死循环looper不会卡死
参考文章:
https://www.zhihu.com/question/34652589