Handler源码分析

本文详细分析了Android中Handler的构造方法、消息发送及处理流程。Handler主要用于线程间通信,通过Looper和MessageQueue实现消息的调度和分发。在主线程中,Handler会从ThreadLocal获取Looper,而在子线程中需先调用Looper.prepare()和Looper.loop()。 sendMessage()方法将Message加入消息队列,遵循时间顺序。Looper的loop()方法不断从队列取消息并分发给相应的Handler进行处理。通过对Handler、Looper和MessageQueue的源码解析,深入理解Android的消息机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Handler有7个构造方法,常用的有:

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

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

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

    //获取Looper实例
    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;
}

在子线程中创建时,就需要调用Looper.prepare()初始化Looper对象,然后必须调用Looper.loop()方法;

在主线程中创建时,会从ThreadLocal中获取mainLooper实例。

发送消息常用的方法,还有其他重载的方法,这里不再列举出来:

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

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

这些方法都会调用sendMessageDelayed(msg,delayMillis)

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

总结:handler.sendMessage(msg)其实只是把我们的Message加入了消息队列,队列采用的

是链表的方式,按照 when 也就是时间排序。没做其他逻辑了。

处理消息的方法,在looper实例的loop()方法里被调用的:

public void dispatchMessage(Message msg) {
    //若msg.callback不为空,则代表使用了post(Runnable r)发送消息
    //此时执行handleCallback(msg),即回调Runnable对象里复写的run()
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        //handler实例的回调不为空
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        
        //执行到这里,说明handler实例的回调为空,
        //此时执行handleMessage(msg)方法,
        //创建Handler实例时复写的方法
        handleMessage(msg);
    }
}

Handler分析完了,接着看Looper类,其构造方法:

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

Looper的构造方法里初始化了消息队列,也获取当前的线程,从这里可以看出,Looper是与线程绑定的,且一个前程只有一个looper实例。

获取子线程的looper实例:

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

获取主线程的looper实例:

public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}

Looper类中最重要的就是消息循环方法:

public static void loop() {
    //获取looper实例
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
     //获取Looper实例中的消息队列对象(MessageQueue)
    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;
        }

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

        //派发消息到对应的Handler,然后handler会处理消息
        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.recycleUnchecked();
    }
}

loop()方法不停的循环获取消息,将消息派发给handler处理。

MessageQueue类主要有两个方法,这里不做详细分析:

enqueueMessage(queue, msg, uptimeMillis):将消息插入消息队列

next():从消息队列中获取消息

至此,Handler相关源码分析完毕。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值