Handler的工作原理

前言

Handler对于大家再也熟悉不过了,在开发中可以说是无处不在,可见其重要性,因此在掌握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());
            }
        }

        mLooper = Looper.myLooper();
        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;
    }

其中参数CallBack为用于处理消息的回调接口,可以为null,参数async注释中描述为如果为true,则handler发送给它的每个相关的Message或发布给相关的Runnable,不太理解,调用的构造方法均传的位false。

FIND_POTENTIAL_LEAKS为标志是否存在内存泄露的情况,如果存在,则会提示泄露相关消息。
然后判断线程中有没有Looper,如果没有则会抛出异常信息 “Can’t create handler inside thread that has not called Looper.prepare()”,无法在未调用Looper.prepare()的线程内创建Handler,下面就是获取到Looper中的MessageQueue。

我们先来看看CallBack接口是什么?

 /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

描述地很清晰:您可以在实例化Handler时使用回调接口来避免必须实现自己的Handler子类。在日常开发中,Handler比较常见的创建方式就是派生一个Handler的子类并重写其handleMessage方法来处理消息,那么CallBack并提供了另一个思路,不想派生子类的时候,我们可以采用Handler handler=new Handler(callback)的方式来创建。

下面是简单测试的小例子…

private Handler mHandler=new Handler(new Handler.Callback() {
       @Override
       public boolean handleMessage(Message msg) {
           switch (msg.what){
               case 1:
                   LogPrint.d("msg....");
                   break;
           }
           return false;
       }
   });

-三个参数的构造方法

 public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通过传入特定的Looper来构造Handler,其中Looper一定不能为空,原因上面已经解释了。
同样,下面是简单测试的小例子…

    Looper looper=Looper.getMainLooper();
    private Handler mHandler=new Handler(looper){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    LogPrint.d("msg....");
                    break;
            }
        }
    };

在了解了Handler的构造方法之后,我们进一步看看Handler的使用,发送消息和接收消息的过程。

发送与处理消息

从Handler发送消息的源码可以看出,最终均会调用sendMessageDelayed这个方法,那我们就从这个方法入手。

 public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

逻辑很简单,继续往里看,看看sendMessageAtTime方法的实现…

 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

到这里就很明显了,发送消息实则只是向消息队列中插入一条消息,Looper不断从消息队列中查询是否有消息,有消息便将消息交由Handler处理,然后Handler的dispatchMessage方法会被调用,这时候Handler就开始处理消息了。

 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

首先判断Message的callback是否为null,不为null就通过handleCallback处理消息,Message的callback实际上就是Handler的post方法所传递的Runnable参数。如果Message的callback为null,则判断mCallback 是否为空,mCallback 在已经涉及,这里不再赘述,mCallback.handleMessage(msg)表示是否需要进一步处理,如果不需要直接retrun,反之,这进行handleMessage(msg)消息处理。

-流程图如下
image.png

为什么在子线程中执行new Handler会抛出异常

开启一个子线程,在子线程中newHandler,报错Log打印如下:

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at com.uniubi.basejavademo.HandlerActivity$1$1.<init>(HandlerActivity.java:23)
        at com.uniubi.basejavademo.HandlerActivity$1.run(HandlerActivity.java:23)
        at java.lang.Thread.run(Thread.java:761)

错误信息:无法在未调用Looper.prepare()的线程内创建Handler。那我们在new Hander之前调用下Looper.prepare(),果然问题解决了,那为什么呢?我们来看看Looper.prepare()方法中都做了什么
代码如下:

 private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

原来是在当前线程中创建了一个Looper,而Looper中又去创建了一个消息队列。子线程中默认不会创建消息队列,而在主线程中系统会去创建主线程的Looper以及MessageQueue,因此如果想在子线程中创建Handler则需要我们自己手动的去调用Looper.prepare(),创建必要的Looper以及MessageQueue。

总结

  • 创建消息

image.png

-发送消息

image.png

-处理消息

image.png

参考文献

  • Android开发艺术探索(第10章 Android的消息机制)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值