Android学习心得(24) --- Android Handler消息机制源码分析

Android Handler消息机制源码分析

相关类

  1. Looper
  2. MessageQueue
  3. Message
  4. Handler

基础知识

1. ThreadLocal

2. epoll

3. pipe

4. idleHandler

使用过程

使用方法:
1、Looper.prepare()
2、创建Handler实例,重写handleMessage处理函数
3、Looper.loop()
4、调用相关的发送Message函数,将消息发送出去
5、调用相关处理函数处理

Looper类

Androidxref.com - Looper.java源码链接

1. prepare()

/** 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()}.
  */
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"); 
        // 每个线程拥有一个Lopper,不能多次创建
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

2. Looper构造函数:

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed); // 创建了对应的MessageQueue
    mRun = true;
    mThread = Thread.currentThread();
}

Looper中会创建MessageQueue,并设置当前运行状态和当前线程

3. Looper对象获取

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static Looper myLooper() {
    return sThreadLocal.get();
}

4. 获取主线程Looper

/** Returns the application's main looper, which lives in the main thread of the application.*/
public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}

5. loop()

负责分发消息,主要通过在for循环中实现
Message msg = queue.next();
msg.target.dispatchMessage(msg);

/**
 * 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();  // 获取Looper
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;  // 获取其MessageQueue

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

MessageQueue

Androidxref - MessageQueue源码链接
Androidxref - android_os_MessageQueue.cpp源码链接
Androidxref - Looper.cpp源码链接
为了能够很多的理解该类的作用,主要从三方面入手:创建过程、消息处理、发送消息
源码中定义了5个native函数,分别实现了MessageQueue的主体功能

private native static int nativeInit();
private native static void nativeDestroy(int ptr);
private native static void nativePollOnce(int ptr, int timeoutMillis);
private native static void nativeWake(int ptr);
private native static boolean nativeIsIdling(int ptr);

1. 创建过程

Looper在创建过程中会创建一个MessageQueue,并将其存放到成员变量mQueue中

// MessageQueue构造函数
MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    mPtr = nativeInit();
}

主要调用了nativeInit()函数来实现创建功能

static jint 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);
    return reinterpret_cast(nativeMessageQueue);
}

NativeMessageQueue函数,该函数功能主要创建本地Looper类对象,从功能函数中可以看到,MessageQueue最后操作的对象还是Native层Looper类对象

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

Looper.cpp构造函数
Looper创建过程主要是创建管道、使用epoll来监听管道上的数据

Looper::Looper(bool allowNonCallbacks) :
        mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
        mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
    int wakeFds[2];
    // 创建匿名管道
    int result = pipe(wakeFds);
    LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);

    mWakeReadPipeFd = wakeFds[0];
    mWakeWritePipeFd = wakeFds[1];

    // 读写管道设置为非阻塞
    result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",
            errno);

    result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",
            errno);

    mIdling = false;

    // Allocate the epoll instance and register the wake pipe.
    // 创建epoll对象并进行注册
    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 = mWakeReadPipeFd;
    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",
            errno);
}

2. 消息处理

MessageQueue.next()用于取出一条消息

Message next() {
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        // 调用本地方法等待nextPollTimeoutMillis,具体等待时候会在下方msg中不断更新
        nativePollOnce(mPtr, nextPollTimeoutMillis);

        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            // mMessages指向队列头
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // 当msg.target为null,即该消息为SyncBarrier,则忽略该消息,并向后找到第一个异步消息
                do {
                    prevMsg = msg;
                    msg = msg.next;
                    // 找到第一个isAsynchronous标志msg
                } 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 = false;
                    // 类似于链表删除,将要处理的消息从中断开
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;  
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (false) Log.v("MessageQueue", "Returning message: " + msg);
                    msg.markInUse();
                    // 返回要处理的消息
                    return msg;  
                }
            } else {
                // No more messages.
                // 当等待时间为-1时阻塞
                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.
        // 当没有消息要处理,检查是否安装了idle回调函数,调用并获取其状态
        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("MessageQueue", "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;  // 重置等待时间
    }
}

nativePollOnce函数,等待功能通过epoll_wait实现

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jclass clazz,
        jint ptr, jint timeoutMillis) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast(ptr);
    nativeMessageQueue->pollOnce(env, timeoutMillis);  // 调用pollOnce
}
void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {
    mInCallback = true;
    mLooper->pollOnce(timeoutMillis);  // 调用Looper pollOnce
    mInCallback = false;
    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
    ...
    ...
   result = pollInner(timeoutMillis);
}
int Looper::pollInner(int timeoutMillis) {
    ...
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
    ...
}

3. 发送消息

向MessageQueue中发送消息使用enqueueMessage
主要是根据时间插入消息,要考虑有SybBarrier和异步消息的情况

boolean enqueueMessage(Message msg, long when) {
    if (msg.isInUse()) {  // 如果消息正在处理,则报错
        throw new AndroidRuntimeException(msg + " This message is already in use.");
    }
    if (msg.target == null) {  // 如果消息target为空,则报错
        throw new AndroidRuntimeException("Message must have a target.");
    }

    synchronized (this) {   // 使用this来同步,表示一次只能有一个进入enqueueMessage
        if (mQuitting) {  
            RuntimeException e = new RuntimeException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w("MessageQueue", e.getMessage(), e);
            return false;
        }

        msg.when = when;
        Message p = mMessages;  // 获取头消息
        boolean needWake;
        // 插入消息操作
        // 1. 当前没有消息,则插入头部
        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.
            // 判断是否有SynBarrier && 是否有异步消息 
            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;
}

Message类

这个就不再多说了,直接给出源码:
Androidxref - Message.java源码链接

Handler类

Handler主要实现的是消息的发送和处理
两种方式: send && post

1. Send

该方法是根据Message自身的ID来判断,从而执行不同的处理操作

public final boolean sendMessage(Message msg);

public final boolean sendEmptyMessage(int what);

public final boolean sendEmptyMessageDelayed(int what, long delayMillis);

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis);

public final boolean sendMessageDelayed(Message msg, long delayMillis);

public boolean sendMessageAtTime(Message msg, long uptimeMillis);

public final boolean sendMessageAtFrontOfQueue(Message msg);

2. Post

而Post方法则是需要有消息的响应代码,不再局限于预定于内容,而是可以定制相关处理方法

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

public final boolean postAtTime(Runnable r, long uptimeMillis)
{
    return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}

public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
    return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}

public final boolean postDelayed(Runnable r, long delayMillis)
{
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

public final boolean postAtFrontOfQueue(Runnable r)
{
    return sendMessageAtFrontOfQueue(getPostMessage(r));
}

最终上述两个方法都会调用enqueueMessage方法添加消息

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

你可能感兴趣的:(Android,android,epoll,源码,handler,消息机制)