初识Android Handler机制

本文深入解析Android中的Handler机制,探讨其工作原理与内部实现细节,包括消息队列、Looper及消息处理流程等内容。

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

Handler在android中主要用于接受子线程的消息,然后在主线程中更新UI。因为android规定,不能在子线程中更新UI。如果在子线程中进行UI操作就会报以下错误:

 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

但是,android又规定,在UI线程,也就是主线程中不能进行耗时操作,比如网络请求,否则可能会产生ANR问题,因此引入了handler机制来对UI进行更新操作。

Handler常用的方法有两种:

<span style="font-size:18px;">public class TestActivity extends AppCompatActivity {

    private static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 方式一
                handler.sendEmptyMessage(0x001);
            }
        }).start();

        //方式二
        new Handler().post(new Runnable() {
            @Override
            public void run() {

            }
        });

    }

}</span>

方式一:就是在主线程中创建handler,通过handler.sendMessage的方法调用主线程中handler的handlerMessage方法处理,从而进行UI更新;

方式二:handler.post(runnable)。来进行一些延时操作。


但是这些方法的使用原理是什么呢,我们来看一下源码。


我们从第一步new handler()开始研究。

<span style="font-size:18px;">    public Handler() {
        this(null, false);
    }</span>
这是new Handler()的构造方法,就是调用了另外一个构造方法,属性设为null,false。

再看其调用的自身的构造方法。

<span style="font-size:18px;">    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;
    }</span>

这里就是对handler进行一些初始化操作,其中关键的代码为:

<span style="font-size:18px;">        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }</span>

这段话的意思就是,获取当前线程的Looper对象,如果当前线程没有创建Looper则会报错:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

意思就是在调用new Handler()前必须调用Looper.prepare()方法,否则就会报错。这里就很奇怪了,我们平常使用过程中也没有调用这个方法,但是程序也没报错啊。这是因为,在Android的入口类:ActivityThread中,main方法已经初始化调用了Looper.prepared()。也就是在主线程中,系统已经默认创建了Looper对象,所以,我们在主线程中new Handler()并不需要自己再去调用一遍。这也就是我们没有去自己写Looper.prepared()的原因。但是,当我们在子线程中去new Handler 的时候必须自己去调用Looper.prepared()否则就会出错。

我们再来顺着看一下Looper.prepared()方法:

<span style="font-size:18px;">    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));
    }</span>

这个方法也很简单,要知道的就是ThreadLocal是什么。

ThreadLocal其实是一个很特殊的类,它可以在不同线程中调用set方法保存自己的值,并且这些值不会因为在其他线程中进行set操作而改变,当前线程只能操作当前线程的值。很适合处理多线程时的场景。

而这里,通过ThreadLocal的get()方法,判断当前线程的Looper对象是否已经存在,如果存在就回报错,因为android规定了一个线程只能调用一次存在一个Looper对象。如果不存在,则创建一个新的looper对象。

我们看一下ThreadLocal的get、set方法。

<span style="font-size:18px;">    public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }</span>

<span style="font-size:18px;">    public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }</span>

可以看到存取的时候都是通过先获取当前的线程,因此ThreadLocal可以保存某个线程的值。

回过头来,我们再看Looper.myLooper()方法:

    public static Looper myLooper() {
        return sThreadLocal.get();
    }
就是通过ThreadLocal获取当前线程的Looper,判断Looper.prepared()是否调用,这样后面的逻辑也想的通了。


顺着代码,我们看一下post()方法,这里就一次性贴出来了,因为post()、postDelayed()等都是层级传递的,比较简单,最终都是调用的sendMessageAtTime()方法:

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

    public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }

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

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

这些方法其实都是顺着调用下来的,还是比较清楚的。

我们看一下最终调用的enqueueMessage方法:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
这里它讲本身赋值给Message的target,所以target是一个handler对象,然后调用了MessageQueue的enqueueMessage方法:

 boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        synchronized (this) {
            if (mQuitting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

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

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

这个方法通过无限循环将Message加入到消息队列,直到没有Message即msg.next==null为止,这也就是根据先进先出的原则来进行排队。但是这里并不是通过队列来实现,而是通过链表,因为我们设置了delay时间,也就是msg.when,这里要先判断时间再进行插入,从而排序。到这里就没有进行下一级调用了。

接下来,我们看一下Looper.loop()方法,其实它和Looper.prepared()所对应,同样系统在主线程中帮我们写好了,所以我们平常不用自己手动调用。


    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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;
            }

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

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

这里是一个无限循环,首先获取当前线程的Looper对象,然后再获取Looper的消息队列。通过循环将消息队列依次操作,直到消息队列为null,跳出循环。那到底是如何调用我们在handler中写的方法的呢。注意到:

 msg.target.dispatchMessage(msg);
而target上面写道,它就是一个当前Looper的handler:
    /**
     * Handle system messages here.
     */
    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,如果是则调用handleCallback方法。
    private static void handleCallback(Message message) {
        message.callback.run();
    }

callback是一个Runnable对象,而这边就是先判断runnable是否为null,不为null则直接调用runnable的run方法,否则调用handlerMessage方法,而这个方法就是我们自己要重写的一个空方法,到这里我们也就知道了handler是如何调用到run 、handlerMessage方法的。
同时还有几个结论:
1、如果handler的runnable不为null,即使后面handler重写了handlerMessage方法依然不会执行;
2、调用handler,如果是在子线程必须加Looper .prepared()、Looper.loop();(一般也不会这么使用)
3、只有调用了Looper.loop()方法,消息才会进行处理。

。。。。。

还有很多不足,欢迎大家指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值