前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅谈 Android Handler

浅谈 Android Handler

作者头像
Android技术干货分享
发布2019-03-27 11:39:08
6240
发布2019-03-27 11:39:08
举报
文章被收录于专栏:Android技术分享Android技术分享

handler是什么?

handler是Android提供用来更新UI的一套消息机制,也是一套消息处理的机制(发送和处理消息)

handler原理

handler负责消息发送,looper负责接收handler发送过来的消息,并把消息发送给handler,messageQueue存储消息的容器

这里先说明一下ThreadLocal,主要在线程中保存变量信息,主要有两个比较重要的方法,一个是get方法,一个是set方法

代码语言:javascript
复制
public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

image.gif

set方法设置当前线程的值,使用键值对的形式存储Thread和looper之间的关系,Thread作为key,looper作为value

代码语言:javascript
复制
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);
    }

image.gif

get方法就是取出当前线程对应的looper,也就是说ThreadLocal是负责thread和looper之间的关系的

下面看一下Looper.prepare()方法

代码语言:javascript
复制
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));
    }

默认情况下ThreadLocal是没有存储的,所以要创建一个新的looper

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

image.gif

默认情况下ThreadLocal是没有存储的,所以要创建一个新的looper

代码语言:javascript
复制
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

image.gif

从looper方法中,创建了一个MessageQueue,在looper中维护着一个消息队列

知道了looper和MessageQueue之后,究竟handler跟这两者有什么关系呢,继续看源码

代码语言:javascript
复制
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;
    }

image.gif

首先调用Looper.myLooper()

代码语言:javascript
复制
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

image.gif

获得当前的looper对象,通过looper拿到MessageQueue,就完成了handler和looper之间的关联

下面继续看handler的消息发送

代码语言:javascript
复制
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);
    }

image.gif

先获得当前的消息队列,如果队列为空就抛出异常,不为空,向消息队列中插入消息

代码语言:javascript
复制
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

image.gif

插入消息之前就指定消息发送给谁(msg.target),默认情况下发送给自己的handler,然后把消息放入队列中,handler就完成了发送message到MessageQueue的过程

那么消息又是如何轮询的呢?

代码语言:javascript
复制
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.recycleUnchecked();
        }
    }

image.gif

通过myLooper()方法获取当前looper,进而获得当前的消息队列,然后通过MessageQueue的next方法获取消息,消息为空时返回,不为空时,调用handler的dispatchMessage(msg)方法,然后这个过程一直循环

代码语言:javascript
复制
public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

image.gif

首先查看msg.callback是否为空,不为空时去调用handleCallback(msg),这个方法在handler的构造方法中存在,可以实现消息的拦截;为空只就

调用handleMessage(msg),这个方法都是大家熟悉的,不在描述,整体的handler的原理就描述到这。

总结

handler在Android中扮演的非常重要的角色,熟悉handler的原理,不仅在面试的时候有用,就连activity的生命周期也是通过handler发送消息,详细请看源码

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.02.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • handler是什么?
  • handler原理
  • 总结
相关产品与服务
消息队列 CMQ 版
消息队列 CMQ 版(TDMQ for CMQ,简称 TDMQ CMQ 版)是一款分布式高可用的消息队列服务,它能够提供可靠的,基于消息的异步通信机制,能够将分布式部署的不同应用(或同一应用的不同组件)中的信息传递,存储在可靠有效的 CMQ 队列中,防止消息丢失。TDMQ CMQ 版支持多进程同时读写,收发互不干扰,无需各应用或组件始终处于运行状态。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档