Android异步消息处理机制总结笔记

出现的原因

解决子线程不能不能执行主线程中操作(主要是更新UI)问题。


更深次原因:

Android机制下不允许将耗时操作放在主线程中执行(比如网络请求等),只能放在子线程中执行,如果在主线程中执行就会抛出异常( CalledFromWrongThreadException:Only the original thread thatcreated a view hierarchy can touch its views.),

  void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

而在执行这些操作之后(比如网络请求),往往会紧接着执行更新UI的操作,而Android机制下,更新UI操作必须在UI线程(UIThread)即主线程(ActivityThread)中执行,否则会导致程序无法响应即ANR,为了解决这种矛盾Android就产生了异步消息处理机制。


延伸:系统为什么不支持在子线程中更新UI?

   这要是因为UI线程不是线程安全的,如果存在多线程并发访问可能会导致UI控件处于不可预期的状态。那么我们可能会问“为什么系统不对UI控件加锁呢?”这样会让UI访问的逻辑变得复杂;其次是锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行,而UI页面的渲染机制在开发中必须是优先得到执行的。所以最简单高效的方式就是采用单线程模式来执行UI操作。

机制概述

     Android的消息机制主要是指的Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程,其实三者实际上是一个整体,只不过我们在开发过程中比较多的接触Handler而已。

 

主要涉及到的类

Handler , Message ,MessageQueue ,Looper

Handler

主要操作: 将一个任务切换到指定的线程中去执行。

1, sendMessage(msg,updataTime)发送消息到子线程中的MessageQueue

2, handMessage(msg)在主线程接收子线程中发送的数据

其他操作:

         1,Handler创建时会采用当前线程的Looper来构建内部的消息循环系统,如果当前线程没有Looper就会报错。

Message

         传递消息和数据的载体

         MessageQueue

          主要功能:可以看做存储消息的队列,虽然名字叫消息队列,但其数据结构是一个单链表(这样插入和删除比较快)。

Looper

          主要功能:循环器,检索消息队列中的消息

异步消息处理机制工作原理

          Hanlder:

当Handler创建完毕后,这时候其内部的Looper以及MessageQueue就可以和Handler一起协同工作了,然后通过Handler的post方法将一个Runnable投递到Handler内部的Looper中去处理,也可以通过Handler的send方法发送一个消息,这个消息也是在Looper中去处理,其实post方法最终也会通过send方法来完成。send方法的工作过程是,最终在send方法中会调用MessageQueue的enqueueMessage方法,将这个消息添加到消息队列中。

 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
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:

MessageQueue是一个单链表结构,主要包含两个操作:插入和读取。读取操作的本身会伴随着删除操作,插入和读取对应的方法分别是enqueueMessage和next,其中enqueueMessage的作用是往消息列表中插入一条消息,而next的作用是从消息队列中取出一条消息,并将其从消息队列中移除。

next方法的主逻辑是:在next方法中有一个无限循环的方法for(;;){},如果消息队列中没有消息,那么next方法就会一直阻塞在这里。当有新消息添加到消息队列时,next方法就会返回这条消息并将其从单链表中移除。

 boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }


Looper:

Looper在Android 的消息机制中扮演者消息循环的角色,具体来说就是它会不停的从MessageQueue中查看是否有新消息,如果有新消息就会立即处理,否则就会一直阻塞在这里。

我们知道,handler的工作需要Looper,没有Looper的线程就会报错。Looper的创建很简单,通过Looper.prepare()即可为当前线程创建一个Looper,接着通过Looper.loop()来开启循环。

new Thread("#ThreadName") {
    @Override
    public void run() {
        super.run();
        //创建Looper的准备
        Looper.prepare();
        Handler handler = new Handler();
        //开始循环
        Looper.loop();
    }
}.start();

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

loop方法的工作过程是:loop方法是一个死循环,唯一跳出循环的方式就是MessageQueue的next方法返回null。当Looper的quit方法被调用时,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出,当消息队列别标记为退出状态是,他的next方法就会返回null。也就是说Looper必须退出,loop方法会调用MessageQueue的next方法来获取新消息,而next是一个阻塞线程,当没有消息的时候,next方法会一直阻塞在哪里,这也导致loop方法会一直阻塞。如果MessageQueue的next方法返回了新消息,Looper就会处理这条消息;msg.target.dispatchMessage(msg),这里的msg.target就是发送这条消息的Handler对象,这样Handler发送的消息最终又交给他的dispatchMessage方法来处理(原来dispatchMessage(msg)是Handler的方法)。但这里不同的而是,Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这样就成功地将代码逻辑切换到指定的线程中去执行了。

  

       延伸:Looper除了prepare方法外,还提供了preparemainLooper方法,这个方法主要是给主线程也就是ActivityThread创建Looper使用的,其本质也就是通过prepare方法来实现的。由于主线程的Looper比较特殊,所以Looper提供了一个getMainLooper方法,可以通过它可以在任何地方获取到主线程的LooperLooper也是可以退出的,Looper提供了quitquitSafely来退出一个Looper,两者的区别在于:qiut会直接退出Looper,而quitSafely只是设定一个退出标记,然后把消息队列中已有消息处理完毕后才完全退出。Looper退出后,通过Handler发送的消息会失败,这时候Handlersend方法会返回false

异步消息处理机制流程:


1, Handler通过sendMessage(msg,updatatime)向子线程中的MessageQueue插入一条消息,其实是在send方法中执行了enqueueMessage方法。

2, 然后MessageQueue的next方法就会返回这条消息给Looper,读取并从单列表中移除这条消息,这其中是Looper一直在无限循环的执行loop方法拿到next的返回值。

3, 这时候Looper收到消息就开始处理了,最终消息由Looper交由Handler处理,即Handler的disPatchMessage方法会被调用。

4, 这时候Handler就开始进去处理消息了,通过CallBack来创建Handler对象:Handler handler = new Handler(callBack);。最后调用Handler的handleMessage方法来处理消息。


猜你喜欢

转载自blog.csdn.net/ding_gc/article/details/52874992