Handler消息机制

来源:互联网 发布:java对于大数的处理 编辑:程序博客网 时间:2024/06/05 20:03

前言

写了很久的一篇文章,因为在群上看到相同的人说起才想到要拿出来分享了。很献丑,哈哈

handler是什么?

我们可以参考一下google文档给出的说明:
handler是一套用于更新UI,发送消息,处理消息的通信机制,当创建handler对象时,会绑定当前线程中的

HandlerThread又是什么?

android中为什么要设计只能通过handler机制更新UI呢?

最根本的原因是解决多线程并发的问题:
假设如果在一个Activity中多个子线程不加锁的情况下去更新UI的后果?必然造成界面更新的错乱。

如果加锁呢?性能下降。

handler机制会把这些更新ui请求放到MessageQueue消息队列中,通过Looper(管理消息队列)的loop()方法一个一个的从队列中读取消息对象,分发到handler对象来处理。

源码分析:

整个应用程序通过ActivityThread创建,并回调各种方法,其中会创建main线程(主线程)在创建main线程中会创建Looper对象,在创建looper时又会创建messagequeue对象。

先详细分析main()主线程的handler机制创建过程:
在ActivityThread类中的main()入口中,执行:

 Looper.prepareMainLooper();

该方法用于创建Looper对象,方法具体实现:

/**     * Initialize the current thread as a looper, marking it as an     * application's main looper. The main looper for your application     * is created by the Android environment, so you should never need     * to call this function yourself.  See also: {@link #prepare()}     为当前的线程创建一个looper对象,使该looper对象作为主线程的looper对象。     这由android环境自己创建的,不需要手动调用     */    public static void prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }

接着是prepare(false)放法的具体实现:

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

其中的sThreadLocal是保存线程信息的,包含set(),get()方法,这里先get()获取,如果能拿到的不为null,则说明已经存在了,不能再创建(抛出异常),保证为空的情况下在创建Looper()对象保存到sThreadLocal中。

接下来再来看下new Looper(boolean)里面做了一些什么,可不仅仅是创建了一个looper对象这么简单哦!

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

可以看到这里还创建了MessageQueue对象以及获取当前的线程实例!为什么要获取当前线程的线程实例呢?别忘了,我们把Looper对象就保存在当前的线程里面的。

继续看回 prepareMainLooper() 方法,在执行完了prepare()方法后,接着执行了myLooper()放法,这方法干嘛的?看下面:

  /**     * Return the Looper object associated with the current thread.  Returns     * null if the calling thread is not associated with a Looper.     */    public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }

前面把Looper对象存到线程中了,现在又执行获取存到线程中的Looper对象。保存在本类中。

至此,Looper()对象跟MessageQueue对象是创建好了。

做个小总结:

对于主线称来说,在程序的入口mian()方法中,自已经自动的生成了Looper对象,以及MessageQueue对象在这里等着你发送消息了。这两个对象在一个线程中只能有一个!

那么写已经创建好的东东什么时候能够发挥作用呢?那当然就是发送消息的时候。
ok执行以下一行代码,发送一条空消息:

Handler handler = new Handler();handler.sendEmtpyMessage();

new Handler()内部调用了多参数的构造方法,吧有用的构造方法贴出来:

 /**     * @param callback The callback interface in which to handle messages, or null.     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.     *     * @hide     */    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;    }

CallBack是用来拦截消息的,等于加上一个预处理,重写的方法返回false则不拦截,ture则拦截。就是酱紫。ok!回到源码,我们能看到:mLooper = Looper.myLooper()这里很重要哦,通过这句代码,Handler和Looper,MessageQueue取得联系。其中的这句异常提醒也是很重要额概念”Can’t create handler inside thread that has not called Looper.prepare()”,不能在一个没有Looper.prepare()的线程中去创建handler,也就是说:handler必要要在存在Looper对象的线程中,如果向子线程这样没有怎么办?那就调用prepare()方法去创建一个呗。

好,然后去利用Looper对象得到MessageQueue对象,你说要这个对象干嘛?稍微发挥我的聪明才智就知道后面是把Message消息添加到MessageQueue队列中去了。

再来看看handler.sendEmtpyMessage(),这里我不贴出来这份代码,因为无论是sendEmptyMessage(),sendMessage(),sendMessageDelay(),post()…都会通过给上默认值最后去到sendMessageAtTime()这个方法。举个例:

public final boolean sendMessageDelayed(Message msg, long delayMillis)    {        if (delayMillis < 0) {            delayMillis = 0;        }        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);    }

因为延时执行的时间实际上就是:当前时间+延时时间=具体时间,所有的时间都能转化为一个具体的时间,so…

那当然是要分析一波sendMessageAtTime的源码了:

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

target是Handler类型的,这里Message持有这个Handler对象,为什么Message要持有handler对象呢?这个问题这里先搁置一下吧。
回来:queue.enqueueMessage(msg,uptimeMills)这个方法就是把一个Message对象添加到MessageQueue队列中。

贴个图:
这里写图片描述