Android应用程序消息处理机制

1,创建线程消息队列

(1) Looper.prepareMainLooper() UI线程消息队列 MessageQueue

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

(2) Looper.prepare() 子线程消息队列 MessageQueue

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //sThreadLocal用来保存当前线程的Looper对象
        sThreadLocal.set(new Looper(quitAllowed));
    }

在Looper的构造方法中  

 private Looper(boolean quitAllowed) {
        //创建当前线程卫唯一的消息队列
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

MessageQueue的构造方法

MessageQueue(boolean quitAllowed) {
     mQuitAllowed = quitAllowed;
    //mPtr为int类型保存了c++层中NativeMessageQueue对象的地址
    /**
     * 创建出c++层中NativeMessageQueue对象,
     * NativeMessageQueue对象会创建c++层Looper对象,
     * Looper对象会创建一个管道,
     * 这个管道的读文件描述符和写文件描述符保存在它的成员变量mWakeReedPipeFd和
     * mWakeReadPipeFd中(int类型)
     * 当一个线程的消息队列没有消息需要处理时,它就会在这个管道的读端文件描述符上进行睡眠等待
     * 直到其他线程通过这个管道的写端文件描述符来唤醒它为止
     */
     mPtr = nativeInit();
}

 

2,消息循环过程 

 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
            //如果msg 为null当前线程会在next()中休眠直到有新的消息要处理为止
            if (msg == null) {
                return;
            }
           ......
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                ......
            }
         ......
        }
    }
    Message next() {
        //用来保存注册到消息队列中空闲消息处理器(IdleHandler)的个数
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        /**
         * nextPollTimeoutMillis为当消息队列中没有新的消息要处理时,当前线程需要
         * 进入休眠等待状态的时间
         * 当nextPollTimeoutMillis = 0 时,表示即使消息队列中没有新的消息要处理,
         * 也不进入睡眠等待状态;如果nextPollTimeoutMillis = -1 时,表示消息队列中
         * 没有新的消息要处理,线程进入睡眠状态,直到被其它线程唤醒
         */
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //检查当前线程的消息队列中是否有新的消息要处理,如果nextPollTimeoutMillis = -1,线程将进入睡眠状态
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }

                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        //还没到达执行消息的时间,nextPollTimeoutMillis线程进入休眠的时间
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        //如果当前线程为睡眠状态mBlocked=true 
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        //取出当前消息返回
                        return msg;
                    }
                } else {
                    // No more messages.
                    //下次调用nativePollOnce(ptr, nextPollTimeoutMillis)时,线程将进入睡眠状态
                    nextPollTimeoutMillis = -1;
                }

           ......

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

}

nativePollOnce(ptr, nextPollTimeoutMillis)是个本地方法,

会调用NativeMessageQueue的pollOnce(nextPollTimeoutMillis)函数;

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,  
        jint ptr, jint timeoutMillis) {  
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);  
    nativeMessageQueue->pollOnce(timeoutMillis);  
}

然后会调用c++层Looper的pollOnce(nextPollTimeoutMillis)函数;

void NativeMessageQueue::pollOnce(int timeoutMillis) {  
    mLooper->pollOnce(timeoutMillis);  
}
 nt Looper::pollInner(int timeoutMillis) {
        ......
        int result = ALOOPER_POLL_WAKE;
        ......
        
        struct epoll_event eventItems[EPOLL_MAX_EVENTS];
//监听注册在前面的所创建的管道(epoll)实例中描述的文件IO读写事件,如果没有IO事件发生,线程就会在epoll_wait()进入睡眠状态,时间为timeoutMillis
        int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
        ......

        size_t requestedCount = mRequestedFds.size();
        int eventCount = poll(mRequestedFds.editArray(), requestedCount, timeoutMillis);
        
        ......
        //检查那个文件发生了IO事件
        for (int i = 0; i < eventCount; i++) {
            int fd = eventItems[i].data.fd;
            uint32_t epollEvents = eventItems[i].events;
            if (fd == mWakeReadPipeFd) {
                //发生IO读写事件的文件描述符是否与当前线程关联的的管道的文件描述符一致
                //返回true说明其他线程向当前线程关联的管道写入了一个新的数据
                //当其他线程想当前线程的消息队列发送一个消息时,他就会向当前线程关联的管道写一个数据,目的是唤醒当前线程,以便它去处理刚刚消息队列接收的消息
                if (epollEvents & EPOLLIN) {
                    //将当前线程关联的管道中的消息读出来,清理旧数据
                    awoken();
                } else {
                    LOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
                }
            } else {
               ......
            }
        }
     ......
        return result;
    }

3,消息的发送过程 

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) {
        //将当前的handler对象赋值给Mesage的target(handler类型)
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

MessageQueue的enqueueMessage()

    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) {
            //消息在使用
            msg.markInUse();
            msg.when = when;
            //mMessages队头的消息
            Message p = mMessages;
            boolean needWake;
            // p == null目标消息队列是个空队列
            // when == 0要插入的消息的优先级最高,要把它插入到消息队列的头部优先执行
            // when < p.when 执行的时间早于P,插入到P前面
            //这三种都需要插入到头部
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                //如果消息不是睡眠状态不需要唤醒,如果mBlocked==true说明线程处于睡眠状态
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                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;
    }

 nativeWake(mPtr)是个本地方法,它由nativeMessageQueue的wake()方法来实现,接着会调用c++层的mLooper->wake()

mLooper调用wake()方法,向它的所描述的管道写一个新的数据,这时候线程会因为这个管道发生了一个IO写事件而被唤醒

4,线程消息处理过程

当一个线程没有消息需要处理时,它就会在c++层的Looper类成员函数pollInner()中被进入睡眠等待状态,因此当这个线程有新的消息要处理时,首先会在c++层的loope类的pollInner()中被唤醒,然后延之前的路径一直返回到java层的Looper类的静态函数loop()中,最后就可以对消息进行处理了

 (1) looper.loop();

    public static void loop() {
        final Looper me = myLooper();
        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;
            }

               ......
           
                msg.target.dispatchMessage(msg);
               ......                      

        }
    }
    public void dispatchMessage(Message msg) {
         //当要处理的消息在发送时指定了一个回调接口时msg.callback != null返回true
         //当调用handler.post(Runable r)时,handler会为这个消息指定一个回调接口
        if (msg.callback != null) { //1
            handleCallback(msg);
        } else {
            //当调用handler的可指定callback构造方法时
            if (mCallback != null) {  //2
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            } 
            handleMessage(msg);//3
        }
    }

    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;//指定一个回调接口
        return m;
    }


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

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

 还有一种消息,线程空闲,不讨论了

猜你喜欢

转载自blog.csdn.net/qq_32671919/article/details/83274944
今日推荐