美文网首页
Android异步消息处理机制

Android异步消息处理机制

作者: 安德雷士 | 来源:发表于2017-03-27 20:52 被阅读0次

    关于Android中的异步消息处理机制,平时在项目中应该算是用的很多了。最近看了一些这方面的源码,记录一下。

    首先,来看一下平时是怎么用的吧。最常见的使用场景,可能就是在子线程中处理一些耗时操作,然后更新UI了。那么,这是怎么做的呢?

    在子线程中处理耗时操作,然后新建了一个Message(这个Message里面会包含很多内容,一会儿再细说),通过一个Handler将Message发送出去。

            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 执行耗时操作
    
                    // 发送消息
                    Message message = Message.obtain();
                    message.what = 1;
                    message.arg1 = 2;
                    handler.sendMessage(message);
                }
            }).start();
    

    在主线程中,我们有一个Handler,并且重写了handleMessage方法,用来接收并处理消息。

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    // 更新UI
    
                }
            }
        };
    

    其实我们常见的就是Handler和Message这两个东西,那么就先来看一下他们到底是什么吧。

    Handler

    A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

    There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

    这个就是官方对Handler的定义,简单来说,Handler就是用来发送和处理Message的,而且很重要的一点,每个Handler的实例都关联了一个线程和这个线程的MessageQueue

    Message

    Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

    什么是Message?Message就是一个包含了描述和任意数据的对象,可以被发送给Handler进行处理。

    While the constructor of Message is public, the best way to get one of these is to call Message.obtain() or one of the Handler.obtainMessage() methods, which will pull them from a pool of recycled objects.

    官方在这里明确表示,虽然Message的构造函数是公有的,但是最好的方式是通过Message.obtain()或者Handler.obtainMessage()之类的方法来创建Message,因为这样会从一个全局的池中来复用Message,而不是每次都新建一个。

        /**
         * Return a new Message instance from the global pool. Allows us to
         * avoid allocating new objects in many cases.
         */
        public static Message obtain() {
            synchronized (sPoolSync) {
                if (sPool != null) {
                    Message m = sPool;
                    sPool = m.next;
                    m.next = null;
                    m.flags = 0; // clear in-use flag
                    sPoolSize--;
                    return m;
                }
            }
            return new Message();
        }
    

    MessageQueue

    Low-level class holding the list of messages to be dispatched by a Looper. Messages are not added directly to a MessageQueue, but rather through Handler objects associated with the Looper.

    前面说了每个Handler的实例都关联了一个MessageQueue,那么MessageQueue是什么?其实从名字就能很容易的看出,MessageQueue就是存储Message的一个队列,先进先出。那么MessageQueue是在哪呢?接下来看另一个很重要的东西Looper。

    Looper

    Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

    其实Looper就是一个无限循环的任务,他不断的从MessageQueue中尝试取出Message,如果没有取到就继续尝试,如果取到了就交给Hander去处理,直到这个循环被停止。

    好了,说了这么多概念,让我们来看看源码。还是从Handler开始,毕竟是直接和我们打交道的。

    无论使用哪种方式创建Handler,最后其实都离不开这两个构造函数。

    1 使用当前线程默认的Looper

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

    2 使用指定的Looper而不是默认的

        public Handler(Looper looper, Callback callback, boolean async) {
            mLooper = looper;
            mQueue = looper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    区别就在于是使用当前线程的默认Looper还是使用指定的Looper了。这里我们可以看到,如果使用的是默认Looper,会调用Looper.myLooper()方法。
    让我们来看看Handler中有哪些常用的方法,基本可以分为两大类post(Runnable r)sendMessage(Message msg),而他们的区别在于post类的方法会调用下面这个方法,指定Message的callback。

        private static Message getPostMessage(Runnable r) {
            Message m = Message.obtain();
            m.callback = r;
            return m;
        }
    

    然后返回一个Message,最终基本上都会调用到这个方法

        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;
            }
            return enqueueMessage(queue, msg, uptimeMillis);
        }
    

    其中MessageQueue queue = mQueue;指定了Handler对应的MessageQueue,然后调用入队列的方法

        private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    

    其中msg.target = this是将Message和Handler绑定在了一起,而queue.enqueueMessage(msg, uptimeMillis)就是将Message入到队列MessageQueue中去。

    Message就是我们需要发送和处理的消息,其中大概包含了这么几个我们需要用到的东西。

    • public int what
      我们自定义的一个类似编号的东西,可以用来与其他Message进行区分
    • public int arg1,arg2
      可以存一些轻量级的数据
    • public Object obj
      可以存对象
    • Bundle data
      用来存储复杂的数据
    • Handler target
      与Message关联的Handler,也就是负责处理消息的Handler
    • Runnable callback
      可以指定运行在某个Runnable上

    再来看一下Looper。

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

    Looper的构造方法中只做了两件事:
    1、生成了一个MessageQueue,这里也就明白了前面说的保存Message的这个队列MessageQueue在哪里了,没错,就是在Looper里。
    2、得到当前所在的线程。
    构造方法做的这两件事很重要,说明了每一个Looper中都包含了一个MessageQueue,并且关联了一个特定的线程,这也是异步消息处理的关键。

    • 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);
        }
    
        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存在,如果存在会抛出异常,因为一个线程中只能有一个Looper存在,如果不存在则创建一个新的Looper,存在一个ThreadLocal里。

        static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    

    我看到网上很多文章在讲Handler机制时并没有过多的提到ThreadLocal,但是其实我觉得这也是很重要的一部分。到底什么是ThreadLocal?简单来说就是将对象在不同线程中分别保存了不同的副本,在某一个线程中改变了对象的值时,并不会影响其他线程中的副本。所以这里用来保存Looper,不同线程中的MessageQueue将会互不影响。
    如果我们在子线程中创建Handler之前不调用prepare方法,将会抛出异常,但是为什么我们在主线程中不需要调用prepare方法呢?那是因为系统会自动调用prepareMainLooper方法为我们创建主线程的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();
            }
        }
    

    而前面在Handler的构造函数中的myLooper方法,只是从ThreadLocal中取出Looper而已。

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

    looper方法就是一个无限循环的任务,不断的从MessageQueue中取出Message进行处理。其中final MessageQueue queue = me.mQueue;就是从当前Looper中取出了MessageQueue,而msg.target.dispatchMessage(msg);就是真正处理消息的地方,其中msg.target就是与Message绑定在一起的那个Handler。

        public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }
    

    callback是什么?callback就是通过post类的方法指定的Runnable,如果callback不为空就执行

        private static void handleCallback(Message message) {
            message.callback.run();
        }
    

    否则就执行handleMessage(msg);

    看到这里不难发现,就像官方的定义那样(废话,当然一样。。。),每个Handler都对应了一个Looper和一个MessageQueue,关联了一个Thread,所以才能实现异步消息处理。比如我们在主线程上创建了一个Handler,就创建了一个Looper和MessageQueue,关联的就是主线程,然后在子线程中发出消息,这个消息就会存储在主线程上的MessageQueue里,并且由Handler进行处理。这样就完成了在子线程中发送消息,在主线程中处理的过程,当然这只是其中的一种应用场景。

    相关文章

      网友评论

          本文标题:Android异步消息处理机制

          本文链接:https://www.haomeiwen.com/subject/deognttx.html