android 深入理解Android消息机制

Messsage、MessageQueue、Looper、Handler的工作原理就像工厂的生产线,Looper就像发送机,MessageQueue相当于传送带,Handler相当于工人,Message相当于待处理的产品。

如下图:

主线程looper创建过程:

 

#ActivityThread
public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
        //1.创建消息循环Looper,就是UI线程的消息队列
        Looper.prepareMainLooper();
       
       //启动ActivityThread,这里最终会启动应用程序。
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        /// M: ANR Debug Mechanism
        mAnrAppManager.setMessageLogger(Looper.myLooper());

       //2.执行消息循环
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

执行ActivityThread.main方法后,应用程序就启动了,UI线程的消息循环也在Looper.loop函数中启动。此后,Looper会一直从消息队列中取出消息,然后处理消息。用户或者系统通过Handler不断往消息队列中添加消息,这些消息不断被取出、处理、回收,使得应用迅速运转起来。

 

#Handler


  /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *(使用{@link Looper}作为当前线程和指定的回调接口,并设置处理程序是否应该是异步的。)
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *(默认情况下,处理程序是同步的,除非使用此构造函数来生成严格异步的处理程序。)(这个与障碍阻塞机制有关吗)
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *(异步消息表示不需要关于同步消息的全局排序的中断或事件。 异步消息不受{@link MessageQueue #enqueueSyncBarrier(long)}引入的同步障碍的影响。)
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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(); //获取Looper
        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;
    }

空参的构造函数主要用于主线程,因为主线程的Looper在ActivityThread的main方法中就被创建了。

从Handler默认 的构造函数中可以看到,Handler会在内部通过Looper.myLooper()来获取Looper对象,并且与之关联,最重要的就是获取到Looper持有的消息队列mQueue。

 /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */(返回与当前线程关联的Looper对象。 如果调用线程未与Looper关联,则返回null。)
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

 

/**
 * 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()}
 */(将当前线程初始化为looper,将其标记为应用程序的主循环。 应用程序的主要循环器是由Android环境创建的,因此您永远不需要自己调用此函数。)
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}
/** 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()}.
      */(将当前线程初始化为looper。这使您有机会创建handlers,然后在实际启动looper之前关联此循环器。)
    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));
    }

是在Looper的prepareMainLooper()方法中,在这个方法中又调用了 prepare(false)方法,在 prepare(false)方法中创建looper并设置到ThreadLocal中,这样,队列就与线程关联上了。

再回到Handler中来,Looper属于某个线程,消息队列存储在Looper,因此,消息队列就通过Looper与特定线程关联上。而Handler又与Looper、消息队列关联,因此,Handler最终就和线程、线程的消息队列关联上了,通过该Handler发送的消息最好就会被执行在这个线程上。

创建了Looper之后,会调用Looper的loop函数,在这个函数中会不断从消息队列中取出、处理消息,具体源码如下:

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */(在此线程中运行消息队列。 务必调用{@link #quit()}来结束循环。)
    public static void loop() {
       //1.获取与当前线程关联的looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
//2.获取与当前线程相关联的消息队列
        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 (;;) {//死循环,即消息循环
           //3.获取消息(might block)
            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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);//处理消息
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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);
            }
//5.回收消息,也就是我们分析享元模式中提到的将Message添加到消息池的操作
            msg.recycleUnchecked();
        }
    }
#MessageQueue


    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
           
             // 1.处理Native层的事件
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
               //2.Java层消息队列
                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) {
                    //msg这个消息有延迟,因此做了一个延迟处理
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

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

next函数的基本思路是从消息队列中依次取出消息,如果这个消息到了执行时间,那么将这条消息返回给Looper,并且将消息列表的指针后移。这个消息队列链表结构与Message中的消息池结构一致。也是通过Message的next字段 将多个Message对象 串连在一起。但是在从消息队列获取消息之前,还有一个nativePollOnce函数调用,第一个参数是mPtr,第二个参数是超时时间。

mPtr存储了Native层的消息队列对象,也就是说Native层还有一个MessageQueue类型。mPtr的初始化是在MessageQueue的构造函数中,如下:

private native static long nativeInit();
//消息队列构造
 MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }

mPtr的值是在nativeInit() 函数中返回。

#android_os_MessageQueue.cpp
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
   //构造NativeMessageQueue
    NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
    if (!nativeMessageQueue) {
        jniThrowRuntimeException(env, "Unable to allocate native queue");
        return 0;
    }

    nativeMessageQueue->incStrong(env);
    //2.将NativeMessageQueue对象转换为一个整型变量
    return reinterpret_cast<jlong>(nativeMessageQueue);
}

我们看到,在nativeInit函数中构造一个NativeMessageQueue 对象,然后将该对象转换为一个整型值,并且返回给Java层,而当Java层需要与Native层的MessageQueue通信时,只要把这个int值传递给Native层,然后Native层通过reinterpret_cast将传递进来的int转换为NativeMessageQueue 指针即可得到这个NativeMessageQueue 对象指针。

下面看一下NativeMessageQueue类的构造函数

NativeMessageQueue::NativeMessageQueue() :
        mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
    mLooper = Looper::getForThread();
    if (mLooper == NULL) {
        mLooper = new Looper(false);
        Looper::setForThread(mLooper);
    }
}

代码很简单,创建了一个Native层的Looper,然后将这个Looper设置给了当前线程。也就是说java层的MessageQueue和Looper在Native层也都有,但是功能并不是一一对应的。

下面看一下NativeMessageQueue类的构造函数

NativeMessageQueue::NativeMessageQueue() :
        mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
    mLooper = Looper::getForThread();
    if (mLooper == NULL) {
        mLooper = new Looper(false);
        Looper::setForThread(mLooper);
    }
}

创建了一个Native层的Looper,然后将这个Looper设置给了当前线程。也就是说java层的MessageQueue和Looper在Native层也都有,但是功能并不是一一对应的。

 

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 | EFD_CLOEXEC);
    LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd: %s",
                        strerror(errno));

    AutoMutex _l(mLock);
    rebuildEpollLocked();
}
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.
  //2.创建epoll文件描述符
    mEpollFd = epoll_create(EPOLL_SIZE_HINT);
    LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(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: %s",
                        strerror(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: %s",
                  request.fd, strerror(errno));
        }
    }
}
sp<Looper> Looper::getForThread() {
    int result = pthread_once(& gTLSOnce, initTLSKey);
    LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");

    return (Looper*)pthread_getspecific(gTLSKey);
}

void Looper::setForThread(const sp<Looper>& looper) {
    sp<Looper> old = getForThread(); // also has side-effect of initializing TLS

    if (looper != NULL) {
        looper->incStrong((void*)threadDestructor);
    }

    pthread_setspecific(gTLSKey, looper.get());

    if (old != NULL) {
        old->decStrong((void*)threadDestructor);
    }
}

首先创建一个管道(pipe),管道本质上是一个文件,一个管道中包含两个文件描述符,分别对应读和写。一般的使用方式是一个线程通过读文件描述符来读取管道内容,当管道没有内容时,这个线程就会进入等待状态;而另一个线程通过写文件描述符来向管道中写入内容,写入内容的时候,如果另一端正有线程正在等待管道中的内容,那么这个线程就会被唤醒。

这个等待和唤醒的操作是通过linux系统epoll机制完成的。要使用Linux系统的epoll操作,首先要通过epoll_create来创建一个epoll专用的文件描述符。最后通过epoll_ctl函数设置监听的事件类型为EPOLLIN。

此时Native层的MessageQueue和Looper就构建完毕了,在底层也通过和epoll建立来了一套消息机制。Native层构建完毕后,则会返回到Java层Looper的构造函数,因此,Java层的Looper和MessageQueue也构建完毕。

 

总结一下:

1.首先构造Java层的Looper对象,Java层looper对象又会在构造 函数中创建Java层的MessageQueue对象。

2.Java层的MessageQueue的构造函数中调用nativeInit函数初始化Native层的NativeMessageQueue,

NativeMessageQueue的构造函数又会建立Native层的looper,并且通过管道和epoll建立一套消息机制。

3.Native层构建完毕后,将NativeMessageQueue对象转化为一个整型值存储到Java层的MessageQueue的mPtr中。

4.启动Java层的消息循环,不断读取、处理消息。

 

这个初始化过程都是在ActivityThread的main函数中完成的,因此,main函数运行之后,UI线程的消息循环就启动了,消息循环不断从消息队列中读取、处理消息,使得系统运转起来。

 

参考《Android源码设计模式》

发布了161 篇原创文章 · 获赞 154 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/zhangying1994/article/details/87161832