Handler机制

源码位置

android-rk3399/frameworks/base/core/java/android/os/Handler.java

Handler构造函数

在新建Handler时,在调用Hander重载函数,源码如下:

  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());
            }
        }
		//通过threadLocal.get获取当前线程的Looper对象
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
      	//获取MessageQueue对象
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Handler是如何和MessageQueue联系起来的?

通过Handler构造函数中的业务逻辑,可以看出先获取looper对象,然后获取looper对象中的MessageQueue对象,这样做的目的是在当前线程中维护一个MessageQueue对象。

sendMessage函数

使用此函数来发送消息,将消息放到MessageQueue的队尾。发送的消息将在handleMessage函数中接收

  public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

sendEmptyMessage函数

此函数用来发送只包含what值的消息。使用场景:当不需要传数据时,可以通过此函数发送一个what值,然后在handleMessage中判断message的what值来执行自己的业务逻辑。

/**
     * Sends a Message containing only the what value.
     *  
     * @return Returns true if the message was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }

enqueueMessage函数

handler中的所有send开头的发送消息都会最终执行到enqueueMessage函数。

   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //调用messagequeue对象的enqueueMessage函数
        return queue.enqueueMessage(msg, uptimeMillis);
    }

handleMessage函数

子类必须实现此函数来接收消息。也就在我们使用handler时需要在此函数中实现接收消息的业务逻辑。

 /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

至此handler的源码分析完毕,里面还有一些其它的函数,在此没有做说明。

Looper

源码位置

Looper.java源码路径为:

android-rk3399/frameworks/base/core/java/android/os/Looper.java
prepare()函数

通过prepare函数可以得知,在一个线程中只会存在一个Looper对象。当多次调用prepare函数时会抛出以下异常。

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {//通过prepare函数可以知道一个线程中只能存在一个Looper对象,否则会抛出以下异常
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //通过ThreadLocal存放一个Looper对象
        sThreadLocal.set(new Looper(quitAllowed));
    }

在主线程中,调用的是prepareMainLooper函数。

image-20211229200348302

我们之所以在activity中不调用prepare()函数就可以直接使用Handler,是因为ActivityThread类的main函数已经帮我们间接调用了prepare函数。ActivityThread的main函数如下图:

image-20211229200732481

Looper()构造函数

在Looper的构造函数中创建一个MessageQueue对象,并获取当前线程对象。源码如下:

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

Looper通过loop()函数中的死循环不断的从MessageQueue中获取Message,然后调用message.target也就是Handler来调度信息。

public static void loop() {
    	/**
    	*  public static @Nullable Looper myLooper() {
        *  return sThreadLocal.get();
    	*	}
    	* 通过myLooper()函数来获取Looper对象。
    	*/
        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;

        //...此处省去多余代码

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
           //...此处省去多余代码
            try {
                //通过msg.target获取Handler对象,然后通过handler对象来调度信息
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
 			//...此处省去多余代码           
        }
    }

Message

message是实现了Parcelable的final类。我们在使用Message类时,最好使用以下的方式

Message message = Message.obtain();

之所以采用上面的方式,官方的解释为:

While the constructor of Message is public, the best way to get
 * one of these is to call {@link #obtain Message.obtain()} or one of the
 * {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
 * them from a pool of recycled objects。
 翻译:
 虽然Message的构造函数是公共的,但获得其中一个的最佳方法是调用{@link obtainMessage . get()}或{@link HandlerobtainMessage Handler.obtainMessage()}方法之一,这将从回收对象池中提取它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

無昂博奥

测试下大赏功能,请勿大赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值