美文网首页
Android: Handler 源码分析

Android: Handler 源码分析

作者: lilykeke | 来源:发表于2021-10-14 16:03 被阅读0次

1. 概述

代码路径

framework/base/core/java/andorid/os/
  - Handler.java
  - Looper.java
  - Message.java
  - MessageQueue.java

1.1 架构介绍:

消息机制主要包含:

  • Message:消息分为硬件产生的消息(如按钮、触摸)和软件生成的消息;
  • MessageQueue:消息队列的主要功能向消息池投递消息(MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next);
  • Handler:消息辅助类,主要功能向消息池发送各种消息事件(Handler.sendMessage)和处理相应消息事件(Handler.handleMessage);
  • Looper:不断循环执行(Looper.loop),按分发机制将消息分发给目标处理者

1.2 应用示例

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                //TODO 定义消息处理逻辑.
            }
        };

        Looper.loop();
    }
}

1.3 ThreadLocal

ThreadLocal: 线程本地存储区(Thread Local Storage,简称为TLS)

每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。TLS常用的操作方法:

  • ThreadLocal.set(T value):将value存储到当前线程的TLS区域,源码如下:
public void set(T value) {
    Thread currentThread = Thread.currentThread(); //获取当前线程
    Values values = values(currentThread); //查找当前线程的本地储存区
    if (values == null) {
        //当线程本地存储区,尚未存储该线程相关信息时,则创建Values对象
        values = initializeValues(currentThread);
    }
    //保存数据value到当前线程this
    values.put(this, value);
}
  • ThreadLocal.get():获取当前线程TLS区域的数据,源码如下:
public T get() {
    Thread currentThread = Thread.currentThread(); //获取当前线程
    Values values = values(currentThread); //查找当前线程的本地储存区
    if (values != null) {
        Object[] table = values.table;
        int index = hash & values.mask;
        if (this.reference == table[index]) {
            return (T) table[index + 1]; //返回当前线程储存区中的数据
        }
    } else {
        //创建Values对象
        values = initializeValues(currentThread);
    }
    return (T) values.getAfterMiss(this); //从目标线程存储区没有查询是则返回null
}

ThreadLocal的get()和set()方法操作的类型都是泛型,接着回到前面提到的sThreadLocal变量,其定义如下:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>()

可见sThreadLocal的get()和set()操作的类型都是Looper类型。

1.4 Message

1.4.1 消息对象

每个消息用Message表示,Message主要包含以下内容:

数据类型 成员变量 解释
int what 消息类别
long when 消息触发时间
int arg1 参数1
int arg2 参数2
Object obj 消息内容
Handler target 消息响应方
Runnable callback 回调方法

创建消息的过程,就是填充消息的上述内容的一项或多项。

1.4.2 消息池

在代码中,可能经常看到recycle()方法,咋一看,可能是在做虚拟机的gc()相关的工作,其实不然,这是用于把消息加入到消息池的作用。这样的好处是,当消息池不为空时,可以直接从消息池中获取Message对象,而不是直接创建,提高效率。

静态变量sPool的数据类型为Message,通过next成员变量,维护一个消息池;静态变量MAX_POOL_SIZE代表消息池的可用大小;消息池的默认大小为50。

消息池常用的操作方法是obtain()和recycle()。

public final Message obtainMessage() {
    return Message.obtain(this);
}

obtain(),从消息池取Message,都是把消息池表头的Message取走,再把表头指向next;

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null; //从sPool中取出一个Message对象,并消息链表断开
            m.flags = 0; // 清除in-use flag
            sPoolSize--; //消息池的可用大小进行减1操作
            return m;
        }
    }
    return new Message(); // 当消息池为空时,直接创建Message对象
}

recycle

recycle(),将Message加入到消息池的过程,都是把Message加到链表的表头;

public void recycle() {
    if (isInUse()) { //判断消息是否正在使用
        if (gCheckRecycle) { //Android 5.0以后的版本默认为true,之前的版本默认为false.
            throw new IllegalStateException("This message cannot be recycled because it is still in use.");
        }
        return;
    }
    recycleUnchecked();
}

//对于不再使用的消息,加入到消息池
void recycleUnchecked() {
    //将消息标示位置为IN_USE,并清空消息所有的参数。
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = -1;
    when = 0;
    target = null;
    callback = null;
    data = null;
    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) { //当消息池没有满时,将Message对象加入消息池
            next = sPool;
            sPool = this;
            sPoolSize++; //消息池的可用大小进行加1操作
        }
    }
}

2. 消息队列的创建

  • 可以在子线程创建handler么?

  • 主线程 Looper 和子线程的 Looper 有什么区别?

  • Handler、 Looper 和 MessageQueue有什么关系?

  • MessageQueue是怎么创建的?

2.1 Handler构造函数

一个例子:

new Thread() {
    
    @Override
    public void run() {
        new Handler();
    }
}.start();

//子线程创建Handler 会抛异常 
//java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare

上面的例子中,子线程中创建Handler,抛异常

源码分析:

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
    //匿名类、内部类或本地类都必须申明为static,否则会警告可能出现内存泄露
    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());
        }
    }

    //必须先执行Looper.prepare(),才能获取Looper对象,否则为null.
    mLooper = Looper.myLooper(); //从当前线程的TLS中获取Looper对象
    
    //获取不到mLooper对象,抛出异常(必须先调用Looper.prepare())
    if (mLooper == null) {
        throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
    }
    
    //消息队列,来自Looper对象
    mQueue = mLooper.mQueue; 
    mCallback = callback; //回调方法
    mAsynchronous = async; //设置消息是否为异步处理方式
}

2.2 Looper 对象的创建和获取

2.2.1 Looper 创建

Looper.prepare()每个线程只允许执行一次

//对于无参的情况,默认调用 prepare(true),表示这个Looper允许退出
//prepare(false),表示不允许退出
public static void prepare() {
    prepare(true);
}

private static void prepare(boolean quitAllowed) {
    //每个线程只允许执行一次该方法,第二次执行时线程的TLS已有数据,则会抛出异常
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //创建Looper对象,并保存到当前线程的TLS区域
    sThreadLocal.set(new Looper(quitAllowed));
}

与prepare() 功能相近,该方法主要在ActivityThread类中使用。

public static void prepareMainLooper() {
    prepare(false); //设置不允许退出的Looper
    synchronized (Looper.class) {
        //将当前的Looper保存为主Looper,每个线程只允许执行一次。
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

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

2.2.2 Looper 构造函数

private Looper(boolean quitAllowed) {
    //创建MessageQueue对象
    mQueue = new MessageQueue(quitAllowed); 
     //记录当前线程.
    mThread = Thread.currentThread();
}

2.3 MessageQueue 对象的创建

2.3.1 java层

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    //通过native方法初始化消息队列,其中mPtr是供native代码使用
    mPtr = nativeInit();
}

2.3.2 native层调用过程

1. android_os_MessageQueue_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);
    return reinterpret_cast<jlong>(nativeMessageQueue);
}

2. NativeMessageQueue()

class NativeMessageQueue : public MessageQueue, public LooperCallback {
public:
    NativeMessageQueue();
    virtual ~NativeMessageQueue();

    virtual void raiseException(JNIEnv* env, const char* msg, jthrowable exceptionObj);

    void pollOnce(JNIEnv* env, jobject obj, int timeoutMillis);
    void wake();
    void setFileDescriptorEvents(int fd, int events);

    virtual int handleEvent(int fd, int events, void* data);

private:
    JNIEnv* mPollEnv;
    jobject mPollObj;
    jthrowable mExceptionObj;
};
NativeMessageQueue::NativeMessageQueue() :
        mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
    //功能类比于Java层的Looper.myLooper(); 获取TLS中的Looper对象
    mLooper = Looper::getForThread();
    if (mLooper == NULL) {
        //创建native层的Looper
        mLooper = new Looper(false);
        //功能类比于Java层的ThreadLocal.set(); 保存native层的Looper到TLS
        Looper::setForThread(mLooper);
    }
}

3. Looper()

Looper::Looper(bool allowNonCallbacks) :
        mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
        mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
        mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
    //构造唤醒事件的fd
    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);
    //重建Epoll事件
    rebuildEpollLocked();
}

Looper对象中的mWakeEventFd添加到epoll监控,以及mRequests也添加到epoll的监控范围内。

void Looper::rebuildEpollLocked() {
    // Close old epoll instance if we have one.
    if (mEpollFd >= 0) {
        //关闭旧的epoll实例
        close(mEpollFd);
    }

    // Allocate the new epoll instance and register the wake pipe.
    mEpollFd = epoll_create(EPOLL_SIZE_HINT);

    struct epoll_event eventItem;
    //把未使用的数据区域进行置0操作
    memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
    eventItem.events = EPOLLIN;//可读事件
    eventItem.data.fd = mWakeEventFd;
    //将唤醒事件(mWakeEventFd)添加到epoll实例(mEpollFd)
    int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);


    for (size_t i = 0; i < mRequests.size(); i++) {
        const Request& request = mRequests.valueAt(i);
        struct epoll_event eventItem;
        request.initEventItem(&eventItem);

         //将request队列的事件,分别添加到epoll实例
        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));
        }
    }
}

3. 消息传递机制

消息是怎么发送的?

  • Handler.sendMessage

消息循环过程是怎样的?

  • Looper.loop

消息是怎么处理的?

  • HandlerDispatchMessage

3.1 消息的发送

Handler.java

public final boolean sendMessageDelayed(Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    //SystemClock.uptimeMillis() + delayMillis 当前时间加上需要延迟的时间
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}

该方法通过设置消息的触发时间为0,从而使Message加入到消息队列的队头。

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    //Handler初始化的时候 mQueue = mLooper.mQueue;
    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, 0);
}

3.1.1 java层:enqueueMessage

Handler.equeueMessage

handler发送消息最终都会调用该方法

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //设置处理消息的target为当前发送消息的handler
    msg.target = this;
    
    //调用默认构造方法 mAsynchronous = false; 默认消息非异步
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

MessageQueue.enqueueMessage

boolean enqueueMessage(Message msg, long when) {
    // 每一个普通Message必须有一个target
    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) {
        //正在退出时,直接返回
        if (mQuitting) {  
            msg.recycle();
            return false;
        }
        
        //标记msg正在使用中
        msg.markInUse(); 
        msg.when = when;
        //mMessages为链表的头结点
        Message p = mMessages;
        boolean needWake;
        
        //p==null 说明当前消息队列为空
        //调用sendMessageAtFrontOfQueue发消息时when==0   
        //when < p.when 表示新来的消息比消息队列头部的消息要早
        if (p == null || when == 0 || when < p.when) {
          
            //当前消息msg放到链表的头结点
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked; //当阻塞时需要唤醒
        } else {
            //如果这个消息不能插入到链表的头结点,接下来找一个合适的位置插进去
            //将消息按时间顺序插入到MessageQueue。
      
            //需要唤醒情况:阻塞了 && 此时消息对列头节点是barrier消息 && 新来的消息是异步消息
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            
            //遍历单链表找到新来消息的合适的位置
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                //新消息未找到合适位置之前,遍历过程中发现异步消息&&需要唤醒时,needWake设置为false
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            //找到合适位置插入链表中
            msg.next = p;
            prev.next = msg;
        }
        //需要唤醒,进入nativeWake流程
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

3.1.2 native层:nativeWake(mPtr)

【1】android_os_MessageQueue_nativeWake()

==> android_os_MessageQueue.cpp

static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->wake(); 【3】
}

【2】NativeMessageQueue::wake()

==> android_os_MessageQueue.cpp

void NativeMessageQueue::wake() {
    mLooper->wake();  【4】
}

【3】Looper::wake()

==> Looper.cpp

void Looper::wake() {
    uint64_t inc = 1;
    // 向管道mWakeEventFd写入字符1
    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
    if (nWrite != sizeof(uint64_t)) {
        if (errno != EAGAIN) {
            ALOGW("Could not write wake signal, errno=%d", errno);
        }
    }
}

其中TEMP_FAILURE_RETRY 是一个宏定义, 当执行write失败后,会不断重复执行,直到执行成功为止。

3.2 消息的循环

消息循环的重点:

  • 取消息 queue.next()

  • 分发消息 msg.target.dispatchMessage(msg);

  • 分发后的Message回收到消息池,以便重复利用

3.2.1 Looper.loop()

public static void loop() {
    final Looper me = myLooper(); //获取TLS存储的Looper对象
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    
    //获取Looper对象中的消息队列
    final MessageQueue queue = me.mQueue; 

    
    Binder.clearCallingIdentity();
    //确保在权限检查时基于本地进程,而不是调用进程。
    final long ident = Binder.clearCallingIdentity();

    //进入loop的主循环方法
    for (;;) {
        //取下一条消息, 可能会阻塞
        Message msg = queue.next();
        //msg == null 表示Looper结束了,直接退出循环
        if (msg == null) {
            return;
        }

        ...
            
        try {
            //用于分发Message
            msg.target.dispatchMessage(msg);
        } finally {
            ...
        }
        ...

        //恢复调用者信息
        final long newIdent = Binder.clearCallingIdentity();
        ...
        //将Message放入消息池 重置一些状态,放入链表中
        msg.recycleUnchecked();
    }
}

3.2.2 java层 : queue.next()

取下一条消息

Message next() {
        
    final long ptr = mPtr;
    if (ptr == 0) { //当消息循环已经退出,则直接返回
        return null;
    }

    
    int pendingIdleHandlerCount = -1;
    
    //初始值设为0 ,表示立即返回
    int nextPollTimeoutMillis = 0;
    
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回
        //nextPollTimeoutMillis = -1 表示一直阻塞,直到有消息
        //第一次调用时nextPollTimeoutMillis = 0 不会阻塞,直接返回
        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
                
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            //从链表的头部取一条消息
            Message msg = mMessages;
            
            
            //如果第一条消息就是屏障,就往后遍历,看看有没有异步消息
            //如果没有,就休眠,等待别人唤醒
            //如果有,就看离这个消息出发时间还有多久,设置一个超时,继续休眠
            if (msg != null && msg.target == null) { 
                //当查询到异步消息,则立刻退出循环
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            
            //拿到一条有用的消息
            if (msg != null) {
                //当消息触发时间大于当前时间,则该消息触发时间还没到,重新设置超时时间
                if (now < msg.when) {
                   
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // 获取一条消息,并返回
                    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();  //设置消息的使用状态,即flags |= FLAG_IN_USE
                    
                    //成功地获取MessageQueue中的下一条即将要执行的消息
                    return msg;  
                }
            } else {
                // msg==null 没有消息的时候,设置该值为-1,下次循环时,会一直阻塞直到有消息
                nextPollTimeoutMillis = -1;
            }
            

            //消息正在退出,返回null
            if (mQuitting) {
                dispose();
                return null;
            }

            //当消息队列为空 msg == null,或者是消息队列的第一个消息还没到时间
            if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                //获取IdleHandlers的个数
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                //没有idle handlers 需要运行,则跳出本次循环
                mBlocked = true;
                continue;
            }

            //有需要运行的 IdleHandler
            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
       }

       //只有第一次循环时,会运行idleHandlers,执行完成后,重置pendingIdleHandlerCount为0.
       for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null;

            boolean keep = false;
            try {
                keep = idler.queueIdle(); //idle时执行的方法
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            //idler.queueIdle() 返回 false, 移除 IdleHandler
            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        //重置idle handler个数为0,以保证不会再次重复运行
        pendingIdleHandlerCount = 0;

        //当调用一个空闲handler时,给nextPollTimeoutMillis设为0,下次循环无需等待直接返回
        nextPollTimeoutMillis = 0;
    }
}

3.2.3 native层:nativePollOnce

代码路径

frameworks\base\core\jni\android_os_MessageQueue.cpp
system\core\libutils\Looper.cpp


frameworks\base\core\jni\android_os_MessageQueue.h
system\core\include\utils\Looper.h

【1】android_os_MessageQueue_nativePollOnce()

==> android_os_MessageQueue.cpp

//初次循环的 timeoutMillis == 0
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj, jlong ptr, jint timeoutMillis) {
    //先将java层传递下来的mPtr转换为nativeMessageQueue
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}

【2】NativeMessageQueue::pollOnce()

==> android_os_MessageQueue.cpp

void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
    mPollEnv = env;
    mPollObj = pollObj;
    //调用到Looper->pollOnce(timeoutMillis)
    mLooper->pollOnce(timeoutMillis);
    mPollObj = NULL;
    mPollEnv = NULL;

    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}

【3】Looper::pollOnce()

==> Looper.h

inline int pollOnce(int timeoutMillis) {
    return pollOnce(timeoutMillis, NULL, NULL, NULL);
}

【4】 Looper::pollOnce()

==> Looper.cpp

/**
 *- timeoutMillis:超时时长
 *- outFd:发生事件的文件描述符
 *- outEvents:当前outFd上发生的事件,包含以下4类事件
 *    - EVENT_INPUT 可读
 *    - EVENT_OUTPUT 可写
 *    - EVENT_ERROR 错误
 *    - EVENT_HANGUP 中断
 *- outData:上下文数据
 */
 
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
    int result = 0;
    for (;;) {
        // 先处理没有Callback方法的 Response事件
        while (mResponseIndex < mResponses.size()) {
            const Response& response = mResponses.itemAt(mResponseIndex++);
            int ident = response.request.ident;
            if (ident >= 0) { //ident大于0,则表示没有callback, 因为POLL_CALLBACK = -2,
                int fd = response.request.fd;
                int events = response.events;
                void* data = response.request.data;
                if (outFd != NULL) *outFd = fd;
                if (outEvents != NULL) *outEvents = events;
                if (outData != NULL) *outData = data;
                return ident;
            }
        }
        if (result != 0) {
            if (outFd != NULL) *outFd = 0;
            if (outEvents != NULL) *outEvents = 0;
            if (outData != NULL) *outData = NULL;
            return result;
        }
        // 再处理内部轮询
        result = pollInner(timeoutMillis); 【5】
    }
}

【5】Looper::pollInner()

==> Looper.cpp

pollOnce返回值说明:

  • POLL_WAKE: 表示由wake()触发,即pipe写端的write事件触发;
  • POLL_CALLBACK: 表示某个被监听fd被触发。
  • POLL_TIMEOUT: 表示等待超时;
  • POLL_ERROR:表示等待期间发生错误;
int Looper::pollInner(int timeoutMillis) {
    ...
    int result = POLL_WAKE;
    mResponses.clear();
    mResponseIndex = 0;
    mPolling = true; //即将处于idle状态
    struct epoll_event eventItems[EPOLL_MAX_EVENTS]; //fd最大个数为16
    //等待事件发生或者超时,在nativeWake()方法,向管道写端写入字符,则该方法会返回;
    //出错eventCount = -1 超时 eventCount = 0
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

    mPolling = false; //不再处于idle状态
    mLock.lock();  //请求锁
    
    if (mEpollRebuildRequired) {
        mEpollRebuildRequired = false;
        rebuildEpollLocked();  // epoll重建,直接跳转Done;
        goto Done;
    }
    
    // epoll事件个数小于0,发生错误,直接跳转Done;
    if (eventCount < 0) {
        if (errno == EINTR) {
            goto Done;
        }
        result = POLL_ERROR; 
        goto Done;
    }
    
    //epoll事件个数等于0,发生超时,直接跳转Done;
    if (eventCount == 0) {  
        result = POLL_TIMEOUT;
        goto Done;
    }

    //循环遍历,处理所有的事件
    for (int i = 0; i < eventCount; i++) {
        int fd = eventItems[i].data.fd;
        uint32_t epollEvents = eventItems[i].events;
        if (fd == mWakeEventFd) {
            if (epollEvents & EPOLLIN) {
                //处理这个事件,即读事件
                awoken(); //已经唤醒了,则读取并清空管道数据
            }
        } else {
            ssize_t requestIndex = mRequests.indexOfKey(fd);
            if (requestIndex >= 0) {
                int events = 0;
                if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
                if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
                if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
                if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
                //处理request,生成对应的reponse对象,push到响应数组
                pushResponse(events, mRequests.valueAt(requestIndex));
            }
        }
    }
Done: ;
    //再处理Native的Message,调用相应回调方法
    mNextMessageUptime = LLONG_MAX;
    while (mMessageEnvelopes.size() != 0) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
        if (messageEnvelope.uptime <= now) {
            {
                sp<MessageHandler> handler = messageEnvelope.handler;
                Message message = messageEnvelope.message;
                mMessageEnvelopes.removeAt(0);
                mSendingMessage = true;
                mLock.unlock();  //释放锁
                handler->handleMessage(message);  // 处理消息事件
            }
            mLock.lock();  //请求锁
            mSendingMessage = false;
            result = POLL_CALLBACK; // 发生回调
        } else {
            mNextMessageUptime = messageEnvelope.uptime;
            break;
        }
    }
    mLock.unlock(); //释放锁

    //处理带有Callback()方法的Response事件,执行Reponse相应的回调方法
    for (size_t i = 0; i < mResponses.size(); i++) {
        Response& response = mResponses.editItemAt(i);
        if (response.request.ident == POLL_CALLBACK) {
            int fd = response.request.fd;
            int events = response.events;
            void* data = response.request.data;
            // 处理请求的回调方法
            int callbackResult = response.request.callback->handleEvent(fd, events, data);
            if (callbackResult == 0) {
                removeFd(fd, response.request.seq); //移除fd
            }
            response.request.callback.clear(); //清除reponse引用的回调方法
            result = POLL_CALLBACK;  // 发生回调
        }
    }
    return result;
}

【6】Looper::awoken()

void Looper::awoken() {
    uint64_t counter;
    //不断读取管道数据,目的就是为了清空管道内容
    TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
}

poll小结

pollInner()方法的处理流程:

  1. 先调用epoll_wait(),这是阻塞方法,用于等待事件发生或者超时;
  2. 对于epoll_wait()返回,当且仅当以下3种情况出现:
    • POLL_ERROR,发生错误,直接跳转到Done;
    • POLL_TIMEOUT,发生超时,直接跳转到Done;
    • 检测到管道有事件发生,则再根据情况做相应处理:
      • 如果是管道读端产生事件,则直接读取管道的数据;
      • 如果是其他事件,则处理request,生成对应的reponse对象,push到reponse数组;
  3. 进入Done标记位的代码段:
    • 先处理Native的Message,调用Native 的Handler来处理该Message;
    • 再处理Response数组,POLL_CALLBACK类型的事件;

从上面的流程,可以发现对于Request先收集,一并放入reponse数组,而不是马上执行。真正在Done开始执行的时候,是先处理native Message,再处理Request,说明native Message的优先级高于Request请求的优先级。

另外pollOnce()方法中,先处理Response数组中不带Callback的事件,再调用了pollInner()方法。

3.3 消息的处理

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //当Message存在回调方法,回调msg.callback.run()方法;
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //当Handler存在Callback成员变量时,回调方法handleMessage();
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //Handler自身的回调方法handleMessage()
        handleMessage(msg);
    }
}

public interface Callback {
        
    public boolean handleMessage(Message msg);
    
}

Handler中使用 post提交: callback = r

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

消息分发的优先级:

  1. Message的回调方法:message.callback.run(),优先级最高;
  2. Handler的回调方法:Handler.mCallback.handleMessage(msg),优先级仅次于1;
  3. Handler的默认方法:Handler.handleMessage(msg),优先级最低。

消息缓存:
为了提供效率,提供了一个大小为50的Message缓存队列,减少对象不断创建与销毁的过程

3.4 消息的移除

public final void removeMessages(int what) {
    mQueue.removeMessages(this, what, null);
}
void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }
    synchronized (this) {
        Message p = mMessages;
        //从消息队列的头部开始,移除所有符合条件的消息
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }
        //移除剩余的符合要求的消息
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

4. 消息的延时机制

  • handler 消息延时机制是如何实现的?

    消息队列按消息触发时间顺序排序

  • 消息延时做了什么特殊处理?

    设置epoll_wait 的超时时间,使其在特定时间唤醒

  • 是发送延时,还是消息处理延时?

  • 延时精度怎么样?

    精度不高,有可能有些消息的处理比较耗时

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) {
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //设置处理消息的target为当前发送消息的handler
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

接下来的分析可以看 3. 消息传递机制-消息的发送

5. IdleHandler

App启动优化涉及到

了解IdleHandler 的作用以及调用方式

了解IdleHandler 有哪些使用场景

熟悉IdleHandler 的实现原理

5.1 IdleHandler原理

MessageQueue.java

/**
 * Callback interface for discovering when a thread is going to block
 * waiting for more messages.
 */
public static interface IdleHandler {
    /**
     * Called when the message queue has run out of messages and will now
     * wait for more.  Return true to keep your idle handler active, false
     * to have it removed.  This may be called if there are still messages
     * pending in the queue, but they are all scheduled to be dispatched
     * after the current time.
     */
    boolean queueIdle();
}
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
    @Override
    public boolean queueIdle() {
        
        //true false 区别
        return false;
    }
});
/**
 * Add a new {@link IdleHandler} to this message queue.  This may be
 * removed automatically for you by returning false from
 * {@link IdleHandler#queueIdle IdleHandler.queueIdle()} when it is
 * invoked, or explicitly removing it with {@link #removeIdleHandler}.
 *
 * <p>This method is safe to call from any thread.
 *
 * @param handler The IdleHandler to be added.
 */
public void addIdleHandler(@NonNull IdleHandler handler) {
    if (handler == null) {
        throw new NullPointerException("Can't add a null IdleHandler");
    }
    synchronized (this) {
        mIdleHandlers.add(handler);
    }
}
Message next() {
    ...  
        
        
    for (;;) {
            

        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            ...
                

            // 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.
            //看消息列表是否有消息可以分发,如果有,就返回该消息
            //走到这里说明,没有消息可以分发,下一个for循环就要进入休眠了
            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);
            }

            //如果keep == flase 需要remove掉 idler
            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;
    }
}

5.2 IdleHandler 在Framework中的使用

void scheduleGcIdler() {
    if (!mGcIdleScheduled) {
        mGcIdleScheduled = true;
        Looper.myQueue().addIdleHandler(mGcIdler);
    }
    mH.removeMessage(H.GC_WHEN_IDLE);
}
final class GcIdler implements  MessageQueue.IdleHandler{

    @Override
    public boolean queueIdle() {
        //实际上调用BinderInternal.forceGc("bg");
        doGcIfNeeded();
        return false;
    }
}

一个例子:等待线程 idle 触发回调

public void waitForIdle(Runnable recipient) {
    mMessageQueue.addIdleHandler(new Idler(recipient));
    mThread.getHandler().post(new EmptyRunnable());
}

private static final class Idler implements MessageQueueIdleHandler{
    
    public final boolean queueIdle() {
        if (mCallback != null) {
            mCallback.run();
        }
        
        //返回false 表示回调是一次性的
        return false;
    }
    
}

5.3 使用场景

  • 延时执行
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.activity_main);
    
    mHandler.postDelayed(new Runnable() {
        
        @Override
        public void run() {
            //执行一些耗时任务,但是要延时多久呢?
            //可以写一个IdleHandler 在主线程空闲的时候执行耗时任务,return false
            doSomething();
        }
        
    }, 1000);
}
  • 批量任务

任务密集

只关注最终结果

开一个工作线程,每一个任务都封装成一个消息,丢到工作线程中。等工作线程空闲下来之后,汇总消息,刷新界面

6. 主线程进入Looper为什么没有ANR

  • 了解ANR触发的原理
  • 了解应用的启动流程
  • 了解线程的消息循环机制
  • 了解应用和系统服务通信的过程

ANR是什么

AMS中 在SystemServer进程

final void appNotResponding() {
    Message msg = Message.obtain();
    msg.what = SHOW_NOT_RESPONDING_MSG;
    
    ...
   //mUiHandler 是 SystemServer的一个子线程     
    mUiHandler.sendMessage(msg);
}

Dialog d = new AppNotResbondingDialog(...);
d.show();

ANR场景:

  • Service Timeout
  • BroadcastQueue Timeout
  • ContentProvider Timeout
  • InputDispatching Timeout

以service为例,看看ANR如何触发

void realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg) {
    ...
    
    bumpServiceExecutingLocked(r, execInFg, "create");
    app.thread.scheduleCreateService(r, ...)
}
void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
    ...
    //启动一个超时机制,如果应用端没有在规定时间启动一个 Service ,就会ANR
    scheduleServiceTimeoutLocked(r.app);
}
void  scheduleServiceTimeoutLocked(ProcessRecord proc) {
    long now = SystemClock.uptimeMillis();
    Message msg = mAm.mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
    mAm.mHandler.sendMessageAtTime(msg, now + SERVICE_TIMEOUT);
}

void serviceTimeout(ProcessRecord proc) {
    ...
    mAm.appNotResponding(...);
}

应用端收到系统服务发过来的启动 service 服务之后

private void handleCreateService(CreateServiceData data) {
    service = (Service)cl.loadClass(data.info.name).newInstance();
    
    ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
    
    Application app = packageInfo.makeApplication(false, mInstrumentation);
    service.attach(...);
    service.onCreate();
    
    ActivityManagerNative.getDefault().serviceDoneExecuting(...);
}

//跨进程调用
private void serviceDoneExecutingLocked(ServiceRecord r, ...) {
    mAm.mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
}
  • anr 是应用没有在规定的时间内完成AMS指定的任务导致的
  • AMS请求调到应用端Binder线程,再丢消息去唤醒主线程来处理
  • ANR不是因为主线程loop循环,而是因为主线程中有耗时任务

7. 消息屏障

消息有三种 :

normal

barrier

async

怎么往消息队列发送消息屏障?

postSyncBarrier只对同步消息产生影响,对于异步消息没有任何差别

private int postSyncBarrier(long when) {
    synchronized(this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        
        //没有target 不需要分发,可以根据target是否为null 判断是否是消息屏障
        msg.makeInUse();
        msg.when = when;
        msg.arg1 = token;
        
        
        //给这个msg按时间顺序插到消息队列
        return token;
    }
}
  • 消息屏障只会影响它后面的消息,它前面的消息不受影响

  • 消息队列可以插入多个消息屏障

  • 消息屏障插到消息队列没有唤醒线程

  • 插入消息屏障会返回一个 token(屏障的一个序列号) 凭借这个token在消息队列中查找消息屏障,然后移除它

  • 只能通过反射调用 postSyncBarrier

删除屏障

public void removeSyncBarrier(int token) {
     synchronized (this) {
         Message prev = null;
         Message p = mMessages;
         //从消息队列找到 target为空,并且token相等的Message
         while (p != null && (p.target != null || p.arg1 != token)) {
             prev = p;
             p = p.next;
         }
         final boolean needWake;
         if (prev != null) {
             prev.next = p.next;
             needWake = false;
         } else {
             mMessages = p.next;
             needWake = mMessages == null || mMessages.target != null;
         }
         p.recycleUnchecked();

         //如果这个线程就是因为这个屏障block住,那么撤除屏障之后,需要唤醒线程
         if (needWake && !mQuitting) {
             nativeWake(mPtr);
         }
     }
 }

相关文章

网友评论

      本文标题:Android: Handler 源码分析

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