您的位置:首页 > 移动开发 > Android开发

android消息机制:Looper,Handler,Message

2015-07-02 14:07 417 查看
首先看下面问题:

1、我们在写代码的时候,不能在非UI线程更新UI界面,所以我们经常会使用Handler来发送一个消息,然后再由Hander来更新UI界面。问题来了:为何Hander能更新UI?

我们可以在android消息机制里面找到这两个问题的答案。

android消息机制主要用到三个类:Looper,Handler,Message.

一、Looper

Looper是用来给线程添加消息循环的,通常线程是没有消息循环的。通过在线程中调用Looper.prepare来初始化消息循环,然后调用Looper.loop方法来处理所有的消息。

如下代码(摘自android API):

<pre name="code" class="java">class LooperThread extends Thread {
public Handler mHandler;

public void run() {
Looper.prepare();

mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};

Looper.loop();
}
}



简单几行代码,线程就拥有消息循环了。它的工作原理是什么呢?让我们来看以下prepare和loop的代码。

<pre name="code" class="java">    public static void prepare() {
prepare(true);
}

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));
}
   private Looper(boolean quitAllowed) {
       <span style="background-color: rgb(255, 255, 102);"> mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();</span>
    }



看高亮背景的两行代码,prepare主要做的事情是,创建一个消息队列,获取当前线程。

初始化完成后,接下来是循环提取消息,并处理消息。这是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 (;;) {
<span style="background-color: rgb(255, 255, 102);"> Message msg = queue.next(); // might block</span>
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);
}

<span style="background-color: rgb(255, 255, 102);">msg.target.dispatchMessage(msg);</span>

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主要做的事情,就是从消息队列里取出消息,然后再丢给Handler去处理。

如果消息队列为空,线程会堵塞,等待下一个消息的到来。

最重要的是消息如何处理,msg.target.dispatchMessage(msg),我们看看这段代码:

<pre name="code" class="java">    public void dispatchMessage(Message msg) {
if (msg.callback != null) {
<span style="background-color: rgb(255, 255, 102);">handleCallback(msg);</span>
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
<span style="background-color: rgb(255, 255, 102);"> handleMessage(msg);</span>
}
}
    private static void handleCallback(Message message) {
        message.callback.run();
    }



当你用Hander.post(runnable)的时候,就会执行handleCallback(msg)。当你重载Handler的handerMessage(msg),调用Handler.sendEmptyMessage等方法的时候,就会在你重载的handlerMessage里处理。

至此,Looper的工作就完成了。简单来说,Looper就是给线程增加了一个消息队列。

接下来的问题是,如何和Hander交互。

二、Handler

Hander 用来往线程的消息队列里发送消息或Runnable。当你在线程中创建一个Hander对象后,这个Hander对象就和这个线程的消息队列关联在一起了。Handler发送的消息都会送到其关系的线程消息队列中去。

Handler有两个功能:1、在指定时间发送一个消息或Runnable。2、跨进程执行,即你可以在另一个线程里,使用Handler发送消息或Runnable, 这个消息会在Hander关联的线程里执行。

比如说,我们启动一个Acticity的时候,就会执行一个主线程(UI线程)。如果你开启一个新线程去做别的事情,比如说下载网络图片。在图片下载完成后,需要把图片设置到ImageView里面。如果直接在你下载的线程里面更新UI,就会出错。这时候,就需要用一个UI线程的Handler来刷新UI。

ok。到源码时间了。看看Handler的构造函数,就知道Handler是如何关联线程的。

public Handler() {
this(null, false);
}
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());
}
}

<span style="background-color: rgb(255, 255, 102);">mLooper = Looper.myLooper();</span>
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
<span style="background-color: rgb(255, 255, 102);"> mQueue = mLooper.mQueue;
mCallback = callback;</span>
mAsynchronous = async;
}
Looper.myLooper()就返回当前线程的Looper,mLooper.mQueue就是Looper的消息队列。

再来看以下,Hanlder发送消息的时候,做了什么事情:

<pre name="code" class="java">   public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, 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);
    }
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        <span style="background-color: rgb(255, 255, 102);">msg.target = this;</span>
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return <span style="background-color: rgb(255, 255, 102);">queue.enqueueMessage(msg, uptimeMillis);</span>
    }



所以,不管调用哪种send message的方法,最终都是调用到enqueueMessage的方法里。

看里面高亮的两行代码:msg.targer = this, 把Hander赋给了Message。这就是我们在loop方法里看到的,msg.target.dispatchMessage(msg),消息会交给Handler处理。

queue.enqueueMessage把消息放到了线程的消息队列里。

Handler还有一个方法,post一个Runnable,最终也是转成发送消息到线程的消息队列。看以下源码:

<pre name="code" class="java">    public final boolean post(Runnable r)
{
return  <span style="background-color: rgb(255, 255, 102);">sendMessageDelayed(getPostMessage(r), 0);</span>
}
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }



以上就是消息机制的基本流程了。

小结一下:如下图,主要的过程就是,Handler发送消息到Looper的MessageQueue, Looper线程分发消息给Handler执行

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: