全面分析Handler消息机制

原文地址为: 全面分析Handler消息机制

      相信Handler大家都很熟悉了,最常见的用法就是在一个线程用Handler对象sendMessage,然后在UI线程该Handler对象执行handleMessage使用Message中的数据去更新UI。

       Handler的最主要作用确实如此,但是作为Android系统一个很重要的组件如果对它的认识不深入点怎么对得起老板发的工资?本文将进一步谈下Handler的运行机制,不会涉及很深入的东西,会就一些相关源码简单分析下总结。

本文要点如下:

1.到底什么是Handler?Handler主要有什么功能?

2.Handler消息机制有哪些相关的类,如何运转?

3.Handler如何实现将消息从一个线程发送到另一个线程?

4.UI线程使用Handler和其他线程使用有什么要注意的,为什么?

5.Handler在Activity中使用的注意要点?

6.Handler还在哪些组件使用?


接下来将把这些问题一一解析。

1.到底什么是Handler?Handler主要有什么功能?

首先,从概念出发,什么是Handler?概念性的东西,还是官网为标准。官方给出的说明是:A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

       简而言之,Handler就是一个和创建当前Handler对象的线程和线程的消息队列绑定的组件,它可以向绑定的消息队列传递Message和Runnable,当消息队列的Message或者Runnable从消息队列取出来的时候去执行它们的相关任务。

        官网接下来又谈了Handler的用处:There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

Handler一般用处有两个,一个是指定任务或者消息在未来某个时间点执行,另一个是指定某种行为在一个不同的线程执行。

看起来似乎不复杂,但是其实信息量很大。首先,消息队列是什么?

Android中消息队列的类为MessageQueue,官方说明:

   Low-level class holding the list of messages to be dispatched by a Looper. Messages are not added directly to a MessageQueue, but rather throughHandler objects associated with the Looper.

You can retrieve the MessageQueue for the current thread with Looper.myQueue().

   

    简而言之MessageQueue就是一个链表,保存着等待被Looper执行的各种消息(Message),而它的消息是由Handler添加进去的。

那Looper是什么鬼?

     对于Looper,官网的说明是Class used to run a message loop for a thread. Threads by default do not have a message loop 

associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process 

messages until the loop is stopped.

  就是说Looper的作用是针对某个线程开启消息循环(循环从消息队列中取出消息执行),线程默认是没有消息循环的,要调用prepare来为当前线程设置一个Looper,调用loop开启消息循环直到循环结束为止。

     简而言之,Handler消息机制主要就是就是Handler、Looper、MessageQueue、Message四人帮一台戏。

2.Handler消息机制有哪些相关的类,如何运转?

以上基本回答了第一个问题,那么第二个问题,Handler消息机制如何运行呢?

   首先看下Handler如何与当前线程绑定?我们看下Handlerd的构造方法:

 public Handler(Callback callback, boolean async) {         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有关,而Handler和线程的绑定就是通过Looper。在这里mLooper = Looper.myLooper();是获得当前线程相关的Looper(因为是构造方法,所以就是创建Handler线程相关的Looper), mQueue = mLooper.mQueue;是获得该Looper对象的消息队列(这又说明了Looper对象持有消息队列的引用),因为Looper和线程关联,所以消息队列和线程关联。

        这样一看,是不是觉得天晴朗了许多?Looper和当前线程关联,消息队列又在Looper中,Handler一旦得到了对应线程的Looper引用,也就和当前线程和消息队列关联上了,不是么?但是,Looper本身又是如何关联上当前线程的?

       点进去看mLooper = Looper.myLooper();的源码:

public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }
      就一行,这个ThreadLocal对象又是什么鬼?

       之前官方说创建一个线程的Looper使用Looper.prepare(),点进去看一下:

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是在ThreadLocal对 象取出来的,而要创建一个 前线程相关的Looper则是通过ThreadLocal对象set出来的(注意到异常信息,说明一个线程关联的Looper只有一个) 是不是隐隐约约觉得Looper和当前线程关联的阴谋就隐藏在这个ThreadLocal类中?

        对于ThreadLocal,它属于java.lang中,官方的说明:

        Implements a thread-local storage, that is, a variable for which each thread  has its own value. All threads share the same ThreadLocal object,but each sees a different value when accessing it, and changes made by one  thread do not affect the other threads. The implementation supports  null values.  

       看起来不好懂。首先必须明确一点,一个线程只能一个Looper对象,从而只有一个MessageQueue(在Looper的构造方法初始化),从上面代码当ThreadLocal对象get方法返回不为空则抛出的异常信息可以看出。大概就是所有的线程共享同一个ThreadLocal对象不同的线程在该对象存储某个变量的值是不同的。比如我们的Looper的prepare()中,当在不同的线程中ThreadLocal对象将新创建的Looper对象set进去的时候,不同线程get出来的Looper都是各自set进去的Looper对象。所以mLooper = Looper.myLooper();的意思就是“把我现在所在的线程的Looper取出来给我吧”的意思(至于ThreadLocal如何实现这看起来很神奇的功能,是因为它内部为不同的线程维护一个数组,每次存取数据都是从对应线程的数组操作的

        所以,Handler关联创建自己对象的线程的过程就是这样子~

        那Handler对象是如何将消息发送到绑定的消息队列(即创建Handler对象的线程关联的消息队列)呢?

       大家都知道Handler发送消息的方法是sendMessage(),看源码:

public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 0);    }
        再看下sendMessageDelayed的源码:

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

      调用了sendMesaageAtTime()再进去:

 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方法,而这个方法会调用消息队列的enqueueMessage方法。前面说过,消息队列实质是一个链表,当handleMessage被调用之后,Message对象会被插入链表,具体源码如下:

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;            }            // We can assume mPtr != 0 because mQuitting is false.            if (needWake) {                nativeWake(mPtr);            }        }        return true;    }
      因为消息可以设置delay 参数,所以在插入链表前还要判断下延时参数when,会根据延时由短到长按顺序插入。

      好了,消息已经插入队列,剩下的工作就是将消息取出来执行。前面说到Looper的消息循环机制,当我们prepare创建了一个当前线程Looper后,调用loop开启消息循环。所以看下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.recycleUnchecked();        }    }
        抛开抛异常和Log代码,其实很简单。就是进入了死循环。不断从自己的消息队列取出消息然后调用 msg.target.dispatchMessage(msg);(取不到则阻塞),而这个msg.target,就是Message对象持有的指向发送的Handler对象的引用,所以现在是调用了发送该Message的Handler对象的dispatchMessage方法去处理这个Message对象。

看下Handler的dispatchMessage的源码:

public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }
       前面几行是判断下Message或者Handler本身是否有设置回调接口(Message的callBack就是Handler所post的Runnable对象),有则调用回调接口去处理Message对象,没有则调用我们熟悉的handleMessage处理Message,至于怎么处理大家都清楚吧。

       总结一下:我们在创建Handler对象的线程外其他的线程通过一个Handler对象发送消息(也可以在本线程去post一个任务),将消息(post出去的Runnable也会被封装为Message)发送到创建Handler对象的线程所关联的Looper对象所持有的消息队列中,然后等待正在消息循环过程中的Looper对象去从队列中取出这个Message,一旦取出该Message,则调用发送该Message的Handler对象的handleMessage方法去处理这个Message。

       可以举一个通俗点的例子。设想一个场景,教室(线程)里的学生(Handler)有很多,只有一个老师(Looper),学生去不同教室(即不是创建该Handler对象的线程)学习写作业(创建Message),然后将作业带到自己教室里按顺序放到老师的桌子上(sendMessage插入消息队列),老师不断按顺序批改作业,每批改完一份作业就叫对应的学生过来拿作业本去修改错误(handleMessage)。

3.Handler如何实现将消息从一个线程发送到另一个线程

这个问题答案上文已经解释了,总结起来就是:这里的关键还是ThreadLocal类,它可以在Handler对象需要与Looper对像关联的时候提供当前

线程的关联的Looper,并从该Looper得到当前线程的消息队列引用,从而使得Handler对象在发送消息的时候可以发送到创建自己的线程的消息队列。而

此时该线程的Looper消息循环执行Message的时候已经在创建Handler的线程中。

4.UI线程使用Handler和其他线程使用有什么要注意的

       UI线程使用Handler大家都很熟悉,但是如果相同的用法放到非UI线程就会出问题,例如在非UI线程使用Handler如下:

 new Thread(){                    @Override                    public void run() {                        Handler handler = new Handler();                    }                }.start();
运行起来肯定报错, 异常信息为"Can't create handler inside thread that has not called Looper.prepare()",即该线程还没有创建Looper。前面的Looper官方说明说过,线程默认不创建Looper,所以要将代码改为这样才可以:

new Thread(){                    @Override                    public void run() {                        Looper.prepare();//创建当前线程的Looper对象                        Handler handler = new Handler();                        Looper.loop(); //开启消息循环                }                }.start();

这时候大家肯定有疑问,为啥UI线程不用创建Looper呢?这就涉及Android的根本机制问题了,因为作为一个使用消息机制处理事件的系统,UI线程本身在初始化工作完成后,就进入Looper的消息循环中,不断等待触发UI改变的相关消息进入UI线程的队列,然后Looper去循环处理。所以UI线程本身一开始就创建了Looper,默认开启了消息循环。

可以看下Android应用的程序的入口方法,ActivityThread的mian方法:

public static void main(String[] args) {        Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        if (false) {            Looper.myLooper().setMessageLogging(new        }        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }
删掉一些和本文无关的代码, 可以看到第二行的Looper.prepareMainLooper();,创建了UI线程的Looper,然后创建了UI线程的Handler,接下来调用Looper的loop启动消息循环,到此UI线程进入处理消息的死循环阶段。

相关资料可参考下:http://stackoverflow.com/questions/35931899/why-main-threads-looper-loop-doesnt-block-ui-thread和http://mattias.niklewski.com/2012/09/android_event_loop.html

5.Handler在Activity中使用的注意要点?

如果你在Activity中这样写Handler:

 Handler handler = new Handler(){            @Override            public void handleMessage(Message msg) {            }        };

IDE会发出警告:This Handler class should be static or leaks might occur。建议将Handler设置为static不然会有内存泄漏的风险。为什么呢?因为这样的写法,实际上是创建了一个继承Handler的Activity匿名内部类,而非静态的内部类会持有外部类的引用(即Activity的引用),而Message又持有了Handler对象的引用,所以如果当一个Message在队列中存放很久的时间或者设置Delay了很久,则Activity的视图和资源都无法及时释放内存。这点可参照谷歌Android Framework 的工程师 Romain Guy说的话:

I wrote that debugging code because of a couple of memory leaks I found in the Android codebase. Like you said, a Message has a 
reference to the Handler which, when it's inner and non-static, has a reference to the outer this (an Activity for instance.) If the Message 
lives in the queue for a long time, which happens fairly easily when posting a delayed message for instance, you keep a reference to the 
Activity and "leak" all the views and resources. It gets even worse when you obtain a Message and don't post it right away but keep it 
somewhere (for instance in a static structure) for later use. 

         他的建议写法是类似这个样子:

 private static class MyHandler extends Handler {    private final WeakReference<SampleActivity> mActivity;    public MyHandler(SampleActivity activity) {      mActivity = new WeakReference<SampleActivity>(activity);    }    @Override    public void handleMessage(Message msg) {      SampleActivity activity = mActivity.get();      if (activity != null) {        // ...      }    }  }
6.Handler还在哪些组件使用

     在安卓系统中,使用Handler的典型组件就是AsynTask,它在执行完doBackGround执行将结果切换到UI线程正是使用Handler。

     看下AsncTask构造方法中初始化后台任务代码:

mWorker = new WorkerRunnable<Params, Result>() {            public Result call() throws Exception {                mTaskInvoked.set(true);                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);                //noinspection unchecked                Result result = doInBackground(mParams);                Binder.flushPendingCommands();                return postResult(result);            }        };
     其中 看到这里执行我们熟悉的doInBackGround方法,然后将该方法的返回值调用postResult方法。看下postResult方法:

private Result postResult(Result result) {        @SuppressWarnings("unchecked")        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,                new AsyncTaskResult<Result>(this, result));        message.sendToTarget();        return result;    }
   这里看到第三行代码将doInBackGround方法的返回值封装为Message使用Handler发出。

  而这里的Handler正是AsyncTask类中的一个内部类:

private static class InternalHandler extends Handler {        public InternalHandler() {            super(Looper.getMainLooper());        }        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})        @Override        public void handleMessage(Message msg) {            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;            switch (msg.what) {                case MESSAGE_POST_RESULT:                    // There is only one result                    result.mTask.finish(result.mData[0]);                    break;                case MESSAGE_POST_PROGRESS:                    result.mTask.onProgressUpdate(result.mData);                    break;            }        }    }

好了,为了让大家更好理解Handler,说了好多有点啰嗦,希望各位看了有所收获吧~~




转载请注明本文地址: 全面分析Handler消息机制

登录后您可以享受以下权益:

×
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他
点击体验
DeepSeekR1满血版
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回顶部