Looper究竟是有什么作用

来源:互联网 发布:产品目录制作软件 编辑:程序博客网 时间:2024/06/10 12:18

说到Handler、MQ、Looper三者之间的关系,想必都很清楚,每一个Thread都有一个Looper对象,Looper对象封装了MQ,然后Handler对象通过向MQ中发消息并去消息来进行工作的,实际上也是Looper通过他的loop()在消息队列中取出消息进行执行。那么问题来了,这个Looper到底是干嘛用的。为什么使用他就可以在线程的消息队列中取消息。接下来会详细地讨论这个问题。

Looper简介

Looper它被设计用来把一个普通的线程变成一个循环线程,然后该线程就具备来循环工作的能力。线程(主线程除外,主线程特例会在后面解释)想要变成循环线程线程需要为该线程指定一个(并且只能指定一个,这个在后面Looper的源码中会得以体现)Looper对象,通常需要进行以下操作:

private class LooperThread extends Thread {            @Override            public void run() {                //将当前线程初始化为looper                Looper.prepare();                // TODO: 16/8/23 初始化handler                //.....               // TODO: 16/8/23 other things                //处理在这个线程中的MQ                Looper.loop();            }        }

可以看到,在当前线程中使用prepare()和loop()方法就可以将该线程变成一个可以循环处理消息线程,并能够开始处理线程中的MQ。为什么就可以变成可以循环工作的线程了呢?直观上看不到,那么就只能看一下Looper的源码了。

可以先看一下Looper中的成员变量和构造函数:

public final class Looper {        private static final String TAG = "Looper";        // sThreadLocal.get() will return null unless you've called prepare().        static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();        private static Looper sMainLooper;  // guarded by Looper.class        final MessageQueue mQueue;        final Thread mThread;        private Printer mLogging;      private Looper(boolean quitAllowed) {            mQueue = new MessageQueue(quitAllowed);            mThread = Thread.currentThread();        }

捡重点的看,首先有一个以Looper对象为value的ThreadLocal(如果对ThreadLocal不清楚的话,可以看一下解密ThreadLocal,或则自己baidu、google)对象sThreadLocal,这样也就可以理解为针对于每个线程来说,会把其对应的Looper对象映射保存在ThreadLocal中;然后有一个sMainLooper主线程的looper对象、消息队列mQueue、线程对象mThread。在构造函数中会为mQueue、mThread初始化,并且mThread就为当前的线程。OK,接下来看上面调用的prepare()具体是怎么实现的:

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

在prepare()中,会创建一个当前线程的Looper对象并把该对象set到ThreadLocal对象中,以保证该Looper对象只能由当前线程进行操作,简而言之在该方法中为当前线程创建一个Looper对象,并把它和当前线程关联起来,使当前线程具有循环工作的特性。但是想要该线程真正的处理MQ中的消息还需要调用接下来的方法:

/**     * 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            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            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();        }    }

同样还是捡重点看,该方法的注释已经说明白“运行该线程上的消息队列,并且别忘了调用quit方法去终止这个loop”。方法中第一句,看一下myLooper()是用来干什么。

final Looper me = myLooper();    public static @Nullable Looper myLooper() {            return sThreadLocal.get();        }

显然用来从sThreadLocal获取当前线程的Looper对象的,这就和上面说的prepare方法的操作对应起来,一个将该线程的Looper对象放到ThreadLocal中,另一个从中去取出当前线程的Looper对象并对其进行一些操作。回到loop方法中,接下来将Looper对象me中的MQ拿出来赋给queue,然后就进入到一个没有任何条件的for循环中,在该for循环中只看以下两句:

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

可以看到在在该循环中不断的在消息队列中去拿消息,并把该消息通过dispatchMessage,然后交给handler去处理消息。

OK,到这里把线程如何指定一个Looper对象以及如何循环处理消息队列介绍完毕。

但是在本文的一开始就说了主线程除外,都知道在android应用的开发中主线程是符合循环线程的特性,但是在主线程并没有调用我们上面说的prepare()和loop()方法,那么具体是怎么实现把主线程也转成循环线程的呢。在Looper的源码中,可以看到

/**         * 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,并且把该looper作为一个应用进程的主looper,而且这个主looper会被Android environment所创建而不需要我们自己调用这个方法。在该方法中所做的主要事情将当前线程的Looper对象赋给sMainLooper,也就是给主线程的Looper初始化。也就说我们在开发过程中主线程肯定是一个Looper线程,只是它被android环境所创建,不需要我们手动的去调用相关的方法来将其转成Looper线程了。

OK,实际上Looper类中还提供了其它的一些方法供给我们使用,例如:

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;            }        }

该方法用于获取主线程的Looper对象sMainLooper,这个在我们创建Handler对象时比较常见,可以看一下Handler的构造函数的两个重载方法:

public Handler(Callback callback, boolean async) {            if (FIND_POTENTIAL_LEAKS) {                final Class<? extends Handler> klass = getClass();                if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&                        (klass.getModifiers() & Modifier.STATIC) == 0) {                    Log.w(TAG, "The following Handler class should be static or leaks might occur: " +                        klass.getCanonicalName());                }            }            mLooper = Looper.myLooper();            if (mLooper == null) {                throw new RuntimeException(                    "Can't create handler inside thread that has not called Looper.prepare()");            }            mQueue = mLooper.mQueue;            mCallback = callback;            mAsynchronous = async;        }
public Handler(Looper looper, Callback callback, boolean async) {            mLooper = looper;            mQueue = looper.mQueue;            mCallback = callback;            mAsynchronous = async;        }

我们只关心其中的Looper对象情况,其它的可以忽略,可以看到在创建Handler对象时候,如果不主动的为该Handler指定其所指向的消息循环Looper的话会默认让该handler指向当前所在的looper线程(可能不是主线程),如果需要给handler指定一个looper线程时,这时候需要传入一个looper对象。通常在某些情况下需要保证handler指向主线程的looper对象时,这时候可以调用getMainLooper()去立即活动主线程的looper对象,并让handler指向该线程。

 Handler hander = new Handler(Looper.getMainLooper);

getThread()

/**         * Gets the Thread associated with this Looper.         *         * @return The looper's thread.         */        public @NonNull Thread getThread() {            return mThread;        }

获取当前looper的线程

quit()方法用来退出当前的Looper

public void quit() {        mQueue.quit(false);    }

OK,到此为止Looper的介绍已经完成,因为考虑到对Handler比较熟悉,而时常忽略了Looper的作用,所以这里单独拿出来说明一下。

ps:对looper的一点总结

1、Looper可以让一个线程具有循环工作的特性,也就说可以把线程编程Looper线程。

2、每个线程只能也最多有一个Looper对象,这个Looper对象是一个Thredlocal,可以保证当前线程操作的Looper对象一定是当前线程自己的。

3、Looper内部又一个MQ,调用loop()方法后线程开始不断的从MQ中去消息交给后面的Handler处理。

0 0