Handler-Message消息机制源码分析

  1. Looper与MessageQueue的初始化

    ​   我们知道每个应用都有一个MainLooper,默认创建的Handler是运行在主线程的,那这一过程是怎么样的呢?原来,在AMS创建Activity的时候,会创建MainLooper并开启消息循环,下面来具体分析下这个过程:

    ​   AMS创建MainLooper:

    // frameworks\base\core\java\android\app\ActivityThread.java
    public static void main(String[] args) {
          
          
          ...
          Process.setArgV0("<pre-initialized>");
          Looper.prepareMainLooper();
          Looper.loop();
    }
    

    ​   经过Looper.prepareMainLooper()->prepare(false)后,Looper创建了mainLooper并保存在sThreadLocal中,同时在执行构造方法的时候创建了MessageQueue

    // frameworks\base\core\java\android\os\Looper.java
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    final MessageQueue mQueue;
    final Thread mThread;
    
    public static void prepareMainLooper() {
          
          
            prepare(false);
            synchronized (Looper.class) {
          
          
                if (sMainLooper != null) {
          
          
                    throw new IllegalStateException("The main Looper has already been prepared.");
                }
                sMainLooper = myLooper();
            }
    }
    
    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));
    }
    
    private Looper(boolean quitAllowed) {
          
          
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
    }
    
    public static @Nullable Looper myLooper() {
          
          
            return sThreadLocal.get();
    }
    

    ​    java层MessageQueue在构造的时候,执行了nativeInit()并将返回值赋给mPtr,下面我们找到对应的cpp

    // frameworks\base\core\java\android\os\MessageQueue.java
    private final boolean mQuitAllowed;
    @SuppressWarnings("unused")
    private long mPtr; // used by native code
     MessageQueue(boolean quitAllowed) {
          
          
            mQuitAllowed = quitAllowed;
            mPtr = nativeInit();
    }
    

    ​   jni层nativeInit()创建了NativeMessageQueue对象,而NativeMessageQueue是c++层MessageQueue的子类,其中在构造NativeMessageQueue()时候创建了c++层的Looper

    // frameworks\base\core\jni\android_os_MessageQueue.cpp
    static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
          
          
        NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
        if (!nativeMessageQueue) {
          
          
            jniThrowRuntimeException(env, "Unable to allocate native queue");
            return 0;
        }
        nativeMessageQueue->incStrong(env);
        return reinterpret_cast<jlong>(nativeMessageQueue);
    }
    
    // frameworks\base\core\jni\android_os_MessageQueue.cpp
    NativeMessageQueue::NativeMessageQueue() :
            mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
        mLooper = Looper::getForThread();
        if (mLooper == NULL) {
            mLooper = new Looper(false);
            Looper::setForThread(mLooper);
        }
    }
    

    ​   下面我们来分析c++层的Looper

    // system\core\libutils\Looper.cpp
    Looper::Looper(bool allowNonCallbacks) :
            mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
            mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
            mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
        mWakeEventFd = eventfd(0, EFD_NONBLOCK);
        LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd.  errno=%d", errno);
    
        AutoMutex _l(mLock);
        rebuildEpollLocked();
    }
    

    ​   上面 rebuildEpollLocked()方法具体如下:其中 mEpollFd = epoll_create(EPOLL_SIZE_HINT),epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem),可以看出这里使用pipe系统调用来创建了一个管道用于进程间的通讯

    void Looper::rebuildEpollLocked() {
        // Close old epoll instance if we have one.
        if (mEpollFd >= 0) {
    #if DEBUG_CALLBACKS
            ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
    #endif
            close(mEpollFd);
        }
    
        // Allocate the new epoll instance and register the wake pipe.
        mEpollFd = epoll_create(EPOLL_SIZE_HINT);
        LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);
    
        struct epoll_event eventItem;
        memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
        eventItem.events = EPOLLIN;
        eventItem.data.fd = mWakeEventFd;
        int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
        LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance.  errno=%d",
                errno);
    
        for (size_t i = 0; i < mRequests.size(); i++) {
            const Request& request = mRequests.valueAt(i);
            struct epoll_event eventItem;
            request.initEventItem(&eventItem);
    
            int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
            if (epollResult < 0) {
                ALOGE("Error adding epoll events for fd %d while rebuilding epoll set, errno=%d",
                        request.fd, errno);
            }
        }
    }
    

    至此,Java层与c++层Looper和Message均已创建完成,总结一下上面的过程:

    • AMS创建activity的时候,创建MainLooper
    • java层Looper创建后会构造MessageQueue,创建jni层
    • jni层NativeMessageQueue创建后,保存在Java层的消息队列对象mQueue的成员变量mPtr中
    • c++层创建Looper后,如果java层消息队列中没有消息,就会使Android应用程序主线程位于等待状态,如果java层消息队列来了消息后,就会唤醒Android应用程序主线程来处理这个消息

2.Looper消息循环

​   Looper不断地遍历消息队列中的消息进行发送,Handler收到消息进行相应的处理

// frameworks\base\core\java\android\os\Looper.java
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();
        }
    }

// frameworks\base\core\java\android\os\Handler.java    
public void dispatchMessage(Message msg) {
    
    
        if (msg.callback != null) {
    
    
            handleCallback(msg);
        } else {
    
    
            if (mCallback != null) {
    
    
                if (mCallback.handleMessage(msg)) {
    
    
                    return;
                }
            }
            handleMessage(msg);
        }
}

3.消息的发送

​   创建一个Handler实例后,相应的Looper与MessageQueue都关联了起来

// frameworks\base\core\java\android\os\Handler.java
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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

   创建一个消息

// frameworks\base\core\java\android\os\Message.java
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();
}

  发送消息:将消息放进消息队列,nativeWake(mPtr)来传递到c++层Looper,通过write方式来往管道到写数据,唤醒Android应用程序主线程。

// frameworks\base\core\java\android\os\Message.java
...
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);
}
// frameworks\base\core\java\android\os\MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
    
    
        ...
        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;
    }

猜你喜欢

转载自blog.csdn.net/wangadping/article/details/114443385