Handler原理解析

2021-11-29  本文已影响0人  jxiang112

Handler可以理解为线程间收发消息的处理器。在Android中最常见的应用场景是子线程使用主线程的Handler发送消息,切换回主线程接收消息并处理消息。
Handler是怎么实现消息的收发的呢
Handler的实现主要需要与Looper、MessageQuere、Message一起实现,它们的关系如下图所示:


Handler关系图

上图含括了消息的收发的大致流程,Looper用于线程循环处理消息处理机制;MessageQuere是缓存消息的队列;Message是消息类,其核心是消息回收复用机制;Handler消息的发送和接收处理器。下面我们从源码的角度去剖析这几个类。

Looper

Looper是用于线程循环处理消息处理机制,如果需要在线程中实现Handler的消息机制,需要在线程中实现Looper的初始化和调用loop方法循环调度消息。我们平常在使用Handler时,并没有对Looper进行初始化和调用loop,那是因为启动应用时,framework已经在主线程实现了,所以如果要在子线程做实现Handler机制,必须要在子线程对Looper进行初始化和调用loop,以下是子线程实现Looper的代码模板(Looper的注释中有说明):

class LooperThread extends Thread {
        public Handler mHandler;
  
        public void run() {
            //初始化Looper
            Looper.prepare();
  
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                }
            };
            //调用loop方法循环处理消息
            Looper.loop();
        }

我们看下Looper的初始化prepare方法的实现代码:

//子线程的初始化
public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            //当前线程已经创建Looper,一个线程不能重复创建Looper并初始化
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //创建Looper并放入ThreadLocal与当前线程进行绑定
        sThreadLocal.set(new Looper(quitAllowed));
    }
 
//主线程的初始化
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

private Looper(boolean quitAllowed) {
        //quitAllowed表示消息队列是否可以释放
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Looper的初始化是通过prepare方法实现,prepare有两个主要的重载,一个是为子线程准备,一个为为主线程,区别是:子线程的消息队列可以释放,而主线程的消息队列不能释放。初始化时创建的Looper放在ThreadLocal与线程进行绑定,所以一般我们判定线程是主线程还是子线程,主要还是通过Looper的进行判断:

public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }
public @NonNull Thread getThread() {
        return mThread;
    }

只要判断Looper.getMainLooper().getThread() 是否与当前线程相等就可以判断当前线程是否是主线程。

我们接着看下loop方法:

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

           //.....
            try {
                //调用msg的target(即Handler)分发消息
                msg.target.dispatchMessage(msg);
               // .....
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //....
            //释放消息,并尝试放入回收池中缓存复用
            msg.recycleUnchecked();
        }
    }

loop方法采用死循环不停的从消息队列中取下一个待处理的消息,调用Handler分发消息,释放消息类并放入缓存复用池。这里不知大家是否有以下的疑问:
a、死循环不停的从消息队列中取消息不会很耗性能吗?
b、如果消息队列中已经没有待处理的消息,loop方法不就退出了吗,那么后面线程再次有消息发送时怎么办?
c、为什么需要将回收的消息类放入池中并复用?
解答:
a、b:不会很耗性能,如果消息队列为空时,线程会挂起释放CPU时间片,等到有新消息时才会唤醒继续执行(MessageQueue源码分析会知道原因)
c:消息收发频繁时,就可以缓解创建消息类的内存和CPU开销,可以提升性能

Message

消息类,它的核心是回收复用机制,我们看下它的源码:

public final class Message implements Parcelable {
   //消息事件编号
    public int what;

   //消息参数int类型
    public int arg1;

   //消息参数int类型
    public int arg2;

    //消息参数object类型
    public Object obj;

     ....
    
    //标识消息已经被使用
    /*package*/ static final int FLAG_IN_USE = 1 << 0;

    /** If set message is asynchronous */
    //标识是异步消息
    /*package*/ static final int FLAG_ASYNCHRONOUS = 1 << 1;

    /** Flags to clear in the copyFrom method */
    //copyFrom方法中要清除的标志
    /*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
    //消息标识位
    /*package*/ int flags;
    //消息处理机时间戳
    /*package*/ long when;
    //消息参数Bundle类型
    /*package*/ Bundle data;
   //消息处理器
    /*package*/ Handler target;
    //消息处理器
    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    //下一个待处理的消息
    /*package*/ Message next;
    
    //回收复用池同步锁
    private static final Object sPoolSync = new Object();
    //回收复用池
    private static Message sPool;
   //回收复用池当前大小
    private static int sPoolSize = 0;
    
    //回收复用池最大容量
    private static final int MAX_POOL_SIZE = 50;
    
    private static boolean gCheckRecycle = true;

    /**  
    尝试从回收复用池中复用被回收的消息类,如果池中没有可复用的则创建一个新的消息
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

   ......

    /**
     回收消息类并尝试放入回收复用池中
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        //将标志位标识为已被使用
        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) {
                //回收复用池没有超过最大值则将被回收消息加入池中
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
    .......

消息类的回收复用池的容量是有限制的,代码中限制为50,在频繁发生消息时回收复用机制可以有效的减小内存和CPU的开销

MessageQueue

消息队列采用什么数据结构呢?根据上面的Message类可以知道:采用的是单链表,消息队列的核心在于消息入队和获取下一个待处理的消息,我们主要针对这两个源码进行解析:

//消息入队,Handler的sendMessage最终会调用MessageQueue的enqueueMessage方法,将消息加入消息队列中
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            //如果消息的目标处理器(即Handler)为空则抛出异常
            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) {
                //消息队列是否中,则是否消息并退出
                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) {
                //如果消息队列为空或者处理的时间为0(即立即处理)或者处理时间比消息队列的队头的时间小
                //则将消息设置为队列的队头
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //如果消息队列不为空并且处理的时间不为0(即非立即处理)并且处理时间比消息队列的队头的时间大
                // 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) {
                //调用native层唤醒被挂起的消息
                nativeWake(mPtr);
            }
        }
        return true;
    }

//获取下一个待处理的消息
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 (;;) {
           //根据nextPollTimeoutMillis设置挂起时间
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            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 = (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;
        }
    }

MessageQueue入队和出队的源码可以知道,消息队列是有优先级的那就是时间,时间小的排在队列的前面,所以出队从队头开始取就可以了。消息入队之后,队列如果处于挂起状态(mBlocked =true)则调用native层进行唤醒。消息出队时如果消息为空或者当前时间比待处理的消息小则需要挂起,当然也可以设置队里空闲是的处理器(平常使用是没有用到)。

Handler

Handler是消息收发处理器,我们来剖析下Handler的关键源码:

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());
            }
        }
        //获取当前创建Handler所在线程的Looper
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        } 
        //获取looper的消息队列
        mQueue = mLooper.mQueue;
        //设置消息出去其
        mCallback = callback;
        //是否是异步
        mAsynchronous = async;
    }

public Handler(Looper looper, Callback callback, boolean async) {
        //设置looper
        mLooper = looper;
        //使用looper的消息队列
        mQueue = looper.mQueue;
        //设置消息处理器
        mCallback = callback;
        //是否是异步
        mAsynchronous = async;
    }
public static Handler getMain() {
        //获取主线程的handler
        if (MAIN_THREAD_HANDLER == null) {
            MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
        }
        return MAIN_THREAD_HANDLER;
    }

public final Message obtainMessage()
    {
        //调用Message的obtain尝试复用消息
        return Message.obtain(this);
    }

//发送消息:待立即处理的消息
public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

//发送消息:延迟delayMillis时间处理消息
public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }

//获取消息并设置消息处理器为runnable
private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

//发送消息:待立即处理的消息
public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
//发送消息:延迟delayMillis时间之后处理消息
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
//发送消息:在uptimeMillis时间点处理消息
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);
        }
        //调用MessageQueue的enqueueMessage将消息加入队列中
        return queue.enqueueMessage(msg, uptimeMillis);
    }
 
//分发消息
public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            //如果消息有处理器(即Runnable),则调用消息的处理器
            handleCallback(msg);
        } else {
            //消息没有处理器
            if (mCallback != null) {
                //如果Handler有自定义处理器
                //则调用Handler的自定义处理器
                if (mCallback.handleMessage(msg)) {
                    //Handler的自定义处理器消耗了该消息,则完成消息处理
                    return;
                }
            }
           /Handler没有自定义处理器,或者Handler的自定义处理器没有消耗该消息,则调用Handler的handleMessage处理消息
            handleMessage(msg);
        }
    }
 //调用消息的处理器(即Runnable)的run方法
private static void handleCallback(Message message) {
        message.callback.run();
    }

Handler发送消息其实调用的是MessageQueue的enqueueMessage方法将消息加入队列中。分发消息时优先使用消息的callback,再者是Handler的callback最后才是Handler的handleMessage。

结合上述代码对消息机制的剖析,希望大家对其原理要理解透,不然比较容易不该出现的问题。

对于Handler常遇到问题及解答:
1、Handler是否可以在子线程中创建?如何在子线程中使用消息机制?
答:Handler是否可以在子线程中创建?——》可以在子线程中创建,前提是:a、在子线程中调用了Looper的prepare和loop,否则发送消息是会报错的,且不能处理UI相关的逻辑,因为是它属于子线程;b、创建时传递UI线程的Looper即mainLooper。如果要Handler处理UI逻辑只能在UI线程中创建或者创建时传递UI线程的Looper(即mainLooper)即可。
如何在子线程中使用消息机制?——》在子线程中调用Looper的prepare和loop
2、Handler send参数基本类型和post有什么区别?如何选择?
答:Handler sendMessage和post有什么区别?——》post会创建Message并调用sendMessage,send参数基本类型也会先创建Message再调用重载发放进行发送消息,两者最终调用的都是MessageQueue的enqueueMessage方法;post的消息处理器是post参数的Runnable,而send参数基本类型的消息处理器是Handler的callback或者handleMessage方法
如何选择?——》个人认为如果业务需要处理的消息种类比较多建议或者传递额外参数用send方式比较好;如果业务消息种类比较少不需要额外参数可以用post比较好
3、Android消息机制使用时如何较小内存和CPU开销?
答:创建消息时用Handler.obtainMessage对消息进行复用
4、Handler是否存在内存泄漏问题?如果有如何处理?
答:Handler是否存在内存泄漏问题?——》一般使用时会有,因为创建的Handler时一般用重写dispatchMessage时或者传递了匿名的Runnable,匿名类经过jvm编译之后内部均持有外部类,这会导致外部类生命周期以及结束,但由于匿名类还持有外部类,而这个你们类是被Message持有的,而Message被MessageQueue持有,而MessageQueue被Looper持有,就会导致外部类得不到及时释放,导致内存泄漏,进而会出现消息异步回调时程序崩溃的问题。
如何处理?——》使用安全的Runnable和安全的Handler,下面是个人的处理方式代码:

public abstract class SafeRunnable<T> extends SafeObject<T> implements Runnable {
    public SafeRunnable(T pObject) {
        super(pObject);
    }

    @Override
    public void run() {
        if(isDestroyed()){
            return;
        }
        try {
            safeRun();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public abstract void safeRun();
}

public abstract class SafeHandler<T> extends Handler {
    private WeakReference<T> mReference;

    public SafeHandler(T pObject){
        mReference = new WeakReference<>(pObject);
    }

    public T getTargetReference(){
        return mReference == null ? null : mReference.get();
    }

    public boolean isDestroyed(){
        T targetObject = getTargetReference();
        if(targetObject == null){
            return true;
        }else if(targetObject instanceof Activity){
            return ((Activity) targetObject).isFinishing() || ((Activity) targetObject).isDestroyed();
        }
        return false;
    }

    @Override
    public void handleMessage(Message msg) {
        if(isDestroyed()){
            return;
        }
        safeHandleMessage(msg);
    }

    public abstract void safeHandleMessage(Message msg);
}

public class SafeObject<T> {
    private WeakReference<T> mReference;

    public SafeObject(T pObject){
        mReference = new WeakReference<>(pObject);
    }

    public T getReferenceTarget(){
        T t = mReference == null ? null : mReference.get();
        return t;
    }

    public void updateReference(T pReference){
        mReference = new WeakReference<>(pReference);
    }

    public boolean isDestroyed(){
        T obj = getReferenceTarget();
        if(obj == null){
            return true;
        }
        if(obj instanceof Activity){
            if(((Activity) obj).isFinishing() || ((Activity) obj).isDestroyed()){
                return true;
            }
        }else if(obj instanceof Fragment){
            if(((Fragment) obj).isDetached()){
                return true;
            }
        }else if(obj instanceof android.support.v4.app.Fragment){
            if(((android.support.v4.app.Fragment) obj).isDetached()){
                return true;
            }
        }
        // Add begin by meitu.weiyx for CR:1010820
        else if(obj instanceof View){
            View view = (View) obj;
            Context context = view.getContext();
            if(context instanceof Activity){
                if(((Activity) context).isFinishing() || ((Activity) context).isDestroyed()){
                    return true;
                }
            }
        }
        // Add end
        return false;
    }

    public void destroy(){
        mReference = null;
    }
}

上述如有错误之处,欢迎各位指正。

上一篇下一篇

猜你喜欢

热点阅读