美文网首页
Android Handler 消息机制

Android Handler 消息机制

作者: xinwa | 来源:发表于2018-04-22 12:15 被阅读0次

    Android 应用程序的每一个线程在启动时,都可以首先在内部创建一个消息队列,然后在进行入到一个无限循环中,不断检查它的消息队列是否有新的消息需要处理,如果没有就会进入睡眠等待状态,直到有新的消息需要处理时。Android只允许在主线程操作UI,故常用Handler发送消息给主线程的消息队列来更新UI。

    附上自己画的流程图

    Handler
    一. 创建线程消息队列
    1. Android应用程序的消息队列是使用MessageQueue对象来描述的,可以调用Looper类的静态函数prepare方法来创建。
    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方法内部又调用了prepare(true),然后创建了Looper对象,Looper对象内部又创建了MessageQueue对象。另外sThreadLocal.set方法将Looper对象保存在了当前线程局部变量中。Looper.myLooper方法可以该变量

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

    2. 主线程的消息队列创建

    public static void main(String[] args) {
           
            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"));
            }
            Looper.loop();
    
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    

    ActivityThread的main()方法如上,当前方法是在主线程运行的,在调用Looper.prepareMainLooper()方法时,就会去创建消息队列,并将创建的Looper对象保存在sMainLooper静态变量中

    二:线程消息的循环过程

    当Android应用程序的消息队列创建好之后,我们就可以调用Looper类的静态成员函数loop使它进入到一个消息循环中

    public class Looper{
    
     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;
            ...
            for (;;) {
                Message msg = queue.next(); // might block
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    return;
                }
            ...
           }
    }
    

    myLooper()方法先取出当前线程的消息队列,然后for循坏不断检查这个消息队列。如果当前线程的消息队列为空,那么queue.next()方法会使线程进入睡眠等待的状态。

    三. 线程消息的发送过程

    1. 创建Handler对象

    public Handler() {
            this(null, false);
    }
    
    public Handler(Callback callback, boolean async) {
           ...
            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;
    }
    

    Handler无參的构造函数,会调用Looper.myLooper()方法,如果创建Handler所在的线程,还没有创建消息队列的时候,那么该方法就去返回空。

    2.消息的发送是使用Handler类的成员函数sendMessage().

    public class Handler{
      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);
      }
    
      private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    }
    

    Handler的sendMessage()方法首先会取出Handler中构建时MessageQueue对象,然后queue.enqueueMessage()方法会将发送的消息根据消息处理的时间先后顺序插入到MessageQueue里

    boolean enqueueMessage(Message msg, long when) {
            if (msg.target == null) {
                throw new IllegalArgumentException("Message must have a target.");
            }
          
            synchronized (this) {
                ...
                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 {
                    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;
                }
                    if (needWake) {
                    nativeWake(mPtr);
                }
            }
            return true;
        }
    

    if (p == null || when == 0 || when < p.when)
    a. 如果当前消息是一个空队列,那么 p = mMessages; 也就是p为空的情况。
    b. 插入的消息的处理事件等于0,也就是when等于0
    c. 插入的消息的处理事件小于消息队列中队头的消息处理事件,这个事件会将needWake 设为true.

    上面这三种情况会将当前消息插入mMessages队列的队头,其他情况则是根据消息处理时间插入到mMessages中。

    3. needWake处理
    needWake为true.那么nativeWake(mPtr)该native方法就会去调用。底层实现是将创建Looper对象的实现,底层会创建一个管道,并利用epoll机制去监听这个管道的读操作符。这里nativeWake()方法正是向这个管道的写描述符写入一个“W”字符,这个时候epoll机制就会去通知由于调用Looper.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;
            for (;;) {
                Message msg = queue.next(); // might block
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    return;
                }
    
                try {
                    msg.target.dispatchMessage(msg);end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
                } finally {
                    if (traceTag != 0) {
                        Trace.traceEnd(traceTag);
                    }
                }
                
            }
        }
    

    当线程从 queue.next()方法处唤醒之后,取出消息队列的对头的消息。msg.target是保存了Handler对象的引用。然后调用Handler的dispatchMessage()方法处理消息

    五:总结

    Android应用程序线程的消息队列,利用c语言底层语言,建立管道,利用epoll机制,与Linux操作系统进行交互,使得线程在消息队列为空的时候进行睡眠等待,等有消息的时候在进行唤醒处理。从而进行页面的绘制,UI方面的处理。故该机制是对于Android系统是非常之重要的。

    另外:Handler、Looper、MessageQueue的相对关系?
    首先Looper是创建线程的消息队列的,那么对于一个线程来说,只会有一个Looper对象。Looper对象创建时又会创建MessageQueue.

    Handler创建时,会拿到当前线程创建的Looper对象。故Handler可以有多个。故多个Handler可以向对应线程的消息队列里面发送消息。

    相关文章

      网友评论

          本文标题:Android Handler 消息机制

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