Android Handler 之原理分析

本文深入解析Android消息机制,包括Handler的源码分析,消息机制成员Message、MessageQueue、Looper的作用及关系,阐述Handler如何发送消息至消息队列,Looper如何循环处理消息。

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

本文主要从几个方面分析Handler:

1.分析Handler的源码

2.简单介绍消息机制中几个成员:Message、MesageQueue、Lopper

3. Handler、Message、MesageQueue、Lopper之间的关系

一.Handler的源码分析:

   上篇文章已经对Handler的使用做了介绍,这里将结合源码进行分析:

   1.首先看下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 " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

 

我们直接看:

mLooper = Looper.myLooper();

    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");

    }

获取当前线程的Looper对象,如果未获取到就抛出异常,这就是上篇文章中在子线程直接new出 Handler时报错的原因。

mQueue mLooper.mQueue;这句用来这里绑定消息队列(MesageQueue)。

 2.接下来我们看下 Handler发送消息的方法:

   (1)sendMessage():

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

      }

调用了一个发送延时消息的方法,延时为0:

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) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);

获取消息队列,如果消息队列为空,抛出异常返回false,消息队列不为null执行enqueueMessage:

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

将Handler发送的消息保存到消息队列中。

boolean enqueueMessage(Message msg, long when) {
    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) {
            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) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // 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;}

(2)post()和postDelayed()方法:

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

}

从两个方法的源码可以看到,post和postDelayed是发送Runnable到消息队列,两个调用的方法都是一样的只是post默认延时为0.之后的发送runnable到消息队列中与sendMessage 是一样的。

接下来我们看下Handler方法中另一个重要的方法:

removeCallbacksAndMessages():

public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);

}

里面调用的是MessagQueue消息队列中的方法:意思就是移除当前handler关联的所有消息,这个方法最好在activity销毁时调用,防止造成内存泄漏。

 

到这里Handler的作用就已经清楚了,发送消息到消息队列(MessageQueue),这边就涉及到消息机制的两个成员Message和MessageQueue:

(1)Message:

    Handler接收与处理的消息对象

(2)MessageQueue:

   存储消息的队列,MessageQueue这里不做源码分析,其实通过看源码可以看到,MessageQueue底层并不是采用队列的方式,而是采用单链表的数据结构来维护消息队列。

 

那么是通过什么来管理MessageQueue的呢这里就涉及到消息机制的最后一个成员Lopper,

 

二.Looper:

    Looper从MessageQueue不断循环取出Message,从上面知道Handler的构造方法中绑定了主线程的looper(主线程在创建时就会默认初始化looper),所以Handler的执行是依赖于Looper所在线程决定的,而子线程默认是没有Looper的所以如果要在子线程中使用Handler就要创建Looper。

来看下Looper的源码:

Looper的成员变量:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;  // guarded by Looper.class

final MessageQueue mQueue;

final Thread mThread;

其中MessageQueue消息队列、Thread线程都熟悉,ThreadLocal会比较少见,这里做个简单的解释:

ThreadLocal实现了一个线程相关的存储,即每个线程都有自己独立的变量。所有的线程都共享者这一个ThreadLocal对象,并且当一个线程的值发生改变之后,不会影响其他的线程的值。

 

接下来我们看下初始化Looper的源码:

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

}

我们看到首先判断当前线程是否已经存在Looper,如果存在就会抛出异常“每个线程只能存在一个Looper”,如果不存在就new Looper,调用Looper的构造方法:

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

 

接下来我们看Looper的Looper.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();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
            SystemProperties.getInt("log.looper."
                    + Process.myUid() + "."
                    + Thread.currentThread().getName()
                    + ".slow", 0);

    boolean slowDeliveryDetected = false;

    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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        try {
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
    }
}

从源码中我们看出 Looper me = myLooper()、MessageQueue queue = me.mQueue;获取到Looper和MessageQueue后就开始无限循环

for (;;) {

        Message msg = queue.next(); // might block

不断的从MessageQueue中取出消息,当获取到Message后就调用msg.target.dispatchMessage(msg);进行处理。

所有Looper最主要两个方法:

1.prepare()初始化Looper

2.loop()开始无限循环取消息。

 

总结:

Android消息机制设计四个成员:Handler、Message、MessageQueue、Looper

Message:消息对象

MessageQueue:存储消息的消息队列,底层采用单链表的数据结构维护消息。

Looper:消息循环,无限循环方式查找消息,有就处理消息,没有就等待,ui线程初始化时默认创建Looper,

所以可以在主线程中new Handler,而子线程中默认没有Looper,在子线程中要new Handler需要先调用Looper.prepare或者获取主线程的looper:Looper.getMainLooper()。

Handler:发送消息和接收消息,Handler的处理逻辑依赖在Looper所在线程。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值