Handler消息机制

来源:互联网 发布:算法 专利 编辑:程序博客网 时间:2024/06/15 10:26

Handler机制的原理,现在几乎成了面试必问问题之一了。也是用的比较多的知识点之一,所以了解它的原理是必需也是必须的。

Handler简介

我们在开发中,经常会遇到一些比较耗时的操作,比如网络访问,下载图片,访问数据库显示等。这些耗时的操作在一定的情况下可能会导致应用发生ANR的问题,通常我们只能开启一个新的线程来执行这些耗时操作。于是在子线程执行完这些操作后,我们需要修改界面上的文字或者显示图片。但是在Android中UI控件不是线程安全的,我们只能在主线程(也是UI线程)中操作UI控件,否则会报错哦。这时候我们就用到了Handler了。

Handler的作用就是将一个任务切换到Handler所在的线程中去执行,所以我们就可以通过Handler将子线程中UI操作切换到UI线程中去了,但前提是Handler要在UI线程中创建哦。

Handler案例

Handler的主要是应用在更新UI线程中的UI控件,它的使用方法也比较简单。只要注意在UI线程中初始化它,重写它的handleMessage(Message msg)方法。在需要更新UI的线程中调用handler.sendMessage(msg)发送消息即可。Handler收到消息后在handleMessage中处理,此时已经切换到了主线程中,示例代码如下:
public class MainActivity extends Activity {    String TAG = "MainActivity";    TextView tv_time;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv_time = (TextView)findViewById(R.id.tv_time);    }    Handler myHandler = new Handler() {          public void handleMessage(Message msg) {                switch (msg.what) {                case 0:                 tv_time.setText("屠龙宝刀");                 break;             case 1:                 tv_time.setText("点击就送");                 break;             case 2:                 tv_time.setText("一刀999级");                 break;             }           }       };       void createThread()    {        new Thread(){            @Override            public void run(){                SystemClock.sleep(3000);                Message msg = new Message();                msg.what = 0;                myHandler.sendMessage(msg);                            SystemClock.sleep(3000);                Message msg_1 = new Message();                msg_1.what = 1;                myHandler.sendMessage(msg_1);                                SystemClock.sleep(3000);                Message msg_2 = new Message();                msg_2.what = 2;                myHandler.sendMessage(msg_2);            }          }.start();    }}

Handler消息机制概述

在了解Handler的消息机制之前,我们先来了解几个知识点。Handler的运行需要下层的MessageQueue和Looper来支持。
MessageQueue消息队列,以链表的形式来存储Handler发送来的消息。
Looper消息循环,Looper会无限的循环去访问MessageQueue消息队列中是否有新消息,如果有则处理,没有则一直等待。

有了基本的知识储备,我们来简单的说一下一个Handler消息的传播过程,首先Handler通过send发出一个消息,这个消息将插入MessageQueue中,Looper循环执行发现MessageQueue中的新消息,取出MessageQueue中的消息到Looper中处理。

消息机制的原理

消息机制的原理,主要就是MessageQueue、Looper和Handler的工作原理,以及他们之前是如何协作的。

MessageQueue的工作原理

MessageQueue消息队列,是在Looper的构造函数中创建的。他是以一种单链表形式的数据结构来维护消息队列的。他的主要操作就是插入(enqueueMessage)和读取(next)。其中读取伴随着删除。我们首先来看一下enqueueMessage的源码:
    boolean enqueueMessage(Message msg, long when) {...        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;    }
从上面enqueueMessage源码可以看出,它就是执行一个插入消息的操作。接下来我们看看MessageQueue的next()操作的源码:
    Message next() {        ...        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            nativePollOnce(ptr, nextPollTimeoutMillis);            synchronized (this) {                // Try to retrieve the next message.  Return if found.                final long now = SystemClock.uptimeMillis();                Message prevMsg = null;                Message msg = mMessages;                if (msg != null && msg.target == null) {                    // Stalled by a barrier.  Find the next asynchronous message in the queue.                    do {                        prevMsg = msg;                        msg = msg.next;                    } while (msg != null && !msg.isAsynchronous());                }                if (msg != null) {                    if (now < msg.when) {                        // Next message is not ready.  Set a timeout to wake up when it is ready.                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);                    } else {                        // Got a message.                        mBlocked = false;                        if (prevMsg != null) {                            prevMsg.next = msg.next;                        } else {                            mMessages = msg.next;                        }                        msg.next = null;                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    nextPollTimeoutMillis = -1;                }                ...            }            ...        }    }
next()操作是一个无限循环操作,只有在获取到msg的时候,才会退出,也就是说在队列没有消息的时候,他会一直阻塞在那里。也从而导致looper循环阻塞在那里,直到有新的消息来到的时候,会立即取出给looper去处理。下面的内容会讲到。而且在msg返回前,会把这个msg从链表中删除。

Looper的工作原理

分析Looper的工作原理,我们首先看一下Looper是怎么创建和调用的。我们可以通过以下的代码,为当前的线程创建一个Looper,并开启消息循环。
new Thread(){    public void run()    {        Looper.prepare();        Handler mHandler = new Handler();        Looper.loop();    }}.start();
我们通过Looper.prepare()初始化当前线程,把它作为一个looper。这里你可以创建handler来引用这个looper,创建handler必须要在调用loop()函数之前。loop()是Looper的最重要的方法,只有调用了它之后,消息系统才会真正的起作用。其源码如下:
    /**     * 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.recycleUnchecked();        }    }
loop()主要是一个无限循环的函数,只有当从MessageQueue中执行next()得到null时才会退出。而MessageQueue的next()方法,在没有消息的时候,会一直阻塞在那里,这时候loop()也就一直阻塞。当有新消息来的时候,next()方法马上返回给looper进行处理。当looper取到msg后,会调用msg.target.dispatchMessage(msg)。这里面的msg.target就是handler,所以把执行消息的操作又还给了handler。

既然loop是一个无限循环的函数,而且是运行在当前线程的,我们来做一个实验,代码如下:
void createThread(){    new Thread(){        @Override        public void run(){            Looper.prepare();            Log.e("MainActivity","this thread : "+this.currentThread()+"  111");            Looper.loop();            Log.e("MainActivity","this thread : "+this.currentThread()+"  222");        }      }.start();}
打印结果如下:
09-13 14:40:23.629: E/MainActivity(2782): this thread : Thread[Thread-35067,5,main]  111
那么结果说明Looper.loop()会阻塞线程,在它之后的代码就不会执行,除非Looper退出。但是问题又来了,我们知道UI线程中也同样使用了Looper,那么他为什么没有阻塞呢?这个下次再讨论。

Handler的工作原理

之前的实例中已经提到了Handler的通常用法。在主线程中初始化Handler对象之后,通过handler的sendMessage(Message msg)来发送消息,之后在handleMessage(Message msg)方法中处理消息。这也就是Handler的主要工作方式,发送消息和接收处理消息。首先我们来看一下Handler发送消息的源码,如下:
    public final boolean sendMessage(Message msg)    {        return sendMessageDelayed(msg, 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);    }    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }
从sendMessage(Message msg)到最后的enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法的一步步调用,其实handler发送消息就是往MessageQueue中插入一条消息。而经过前面的MessageQueue和Looper的分析,之后由loop循环从消息队列中取出消息msg又交给了handler处理了。调用了Handler的dispatchMessage(Message msg)方法。接下来我们再来看看dispatchMessage方法的源码:
    public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }
dispatchMessage(Message msg)方法中首先判断msg是否有callback接口,再判断是否有mCallback,如果都没有,则调用handleMessage(Message  msg),handleMessage(Message msg)就是我们在之前的实例中提到的需要重写的方法。

这样整个Handler消息机制就完整起来了。

本文地址,欢迎关注博客


2 0
原创粉丝点击