Android 消息机制源码分析

概述

大多数的UI框架都是采用单线程模型设计的,例如Java Swing 和 Android UI,Android应用启动时就会为应用创建一个主线程,由于UI操作都是在主线程中进行的,所以主线程也称为 。在单线程模式下,UI线程执行耗时很长的操作(例如,网络访问或数据库查询)将会阻塞UI线程。一旦UI线程被阻塞,将无法分派任何事件,包括绘图事件。从用户的角度来看,应用好像挂掉了。 更糟糕的是,如果 UI 线程被阻塞超过几秒钟时间(目前大约是 5 秒钟),用户就会看到一个让人厌烦的“应用无响应”(ANR) 对话框。如果引起用户不满,他们可能就会决定退出并卸载此应用。
Android UI工具包并非是线程安全的。因此不能通过工作线程操作UI,而只能通过UI线程操作UI。
综上所述 Android的单线程模式必须遵守以下两条规则:
1 不要阻塞 UI 线程
2 不要在 UI 线程之外操作UI

正是因为不要阻塞 UI 线程,所以我们将耗时的操作放到工作线程中,如果在工作线程处理耗时操作的过程中需要更新UI界面,但是由于不可以在工作线程中操作UI的限制,这时我们就要用Android消息机制(即Handler机制)来将更新UI界面的操作切换到UI线程中执行,这也是Google设计Handler机制的初衷。

预备知识

1 ThreadLocal

通常来说,当某些数据以线程做为作用域并且不同线程具有不同数据副本的时候,就可以考虑使用ThreadLocal实现。在Handler机制中,Looper对象就是以线程做为作用域并且不同的线程中Looper对象是不同的,因此Android系统中选择通过ThreadLocal实现Looper对象的存取。下面举例说明一下ThreadLocal使用方法。
代码如下:

final ThreadLocal<Integer> threadLocal1 = new ThreadLocal<Integer>();
final ThreadLocal<String> threadLocal2 = new ThreadLocal<String>();
threadLocal1.set(5);
threadLocal2.set("one");
Log.d(TAG, "Thread1 threadLocal1.get() = " + threadLocal1.get());
Log.d(TAG, "Thread1 threadLocal2.get() = " + threadLocal2.get());

new Thread(new Runnable() {
    @Override
    public void run() {
        threadLocal1.set(9);
        threadLocal2.set("two");
        Log.d(TAG, "Thread2 threadLocal1.get() = " + threadLocal1.get());
        Log.d(TAG, "Thread2 threadLocal2.get() = " + threadLocal2.get());
    }
}).start();

new Thread(new Runnable() {
    @Override
    public void run() {
        Log.d(TAG, "Thread3 threadLocal1.get() = " + threadLocal1.get());
        Log.d(TAG, "Thread3 threadLocal2.get() = " + threadLocal2.get());
    }
}).start();

运行结果如下:

D/com.cytmxk.test.thread.ThreadLocalFragment: Thread1 threadLocal1.get() = 5
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread1 threadLocal2.get() = one
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread2 threadLocal1.get() = 9
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread2 threadLocal2.get() = two
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread3 threadLocal1.get() = null
D/com.cytmxk.test.thread.ThreadLocalFragment: Thread3 threadLocal2.get() = null

从上面的运行结果就可以得出结论:
1 通过ThreadLocal对象保存的数据是以线程作为作用域并且不同线程具有不同的数据副本。
2 通过ThreadLocal在某个线程保存数据后,在其他的线程中获取的数据为null。
3 一个线程中可以保存多个数据(最多16个,下面分析源码时会说明)。

现在我们从源码的角度来分析ThreadLocal的工作原理,从而印证我上面的到的结论。对于ThreadLocal这种数据获取和保存的类,只要了解了获取和保存数据的方法就可以明白其工作原理。下面我们就先来看一下ThreadLocal保存数据的set方法:

public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
        values = initializeValues(currentThread);
    }
    values.put(this, value);
}

有上面的代码可知,set方法中先会获取执行set方法线程的实例currentThread,然后执行values方法获取currentThread的成员变量localValues(ThreadLocal.Values类型)的值然后赋值给values;如果values为null(说明是第一次在currentThread线程中使用ThreadLocal的set方法),就会调用initializeValues方法为currentThread线程的成员变量localValues进行初始化(localValues的成员变量table被初始化为长度为32的数组)并且将初始化后的localValues赋值给values;接着就会调用values的put方法,先来看一下values的put方法:

void put(ThreadLocal<?> key, Object value) {
    cleanUp();

    // Keep track of first tombstone. That's where we want to go back
    // and add an entry if necessary.
    int firstTombstone = -1;

    for (int index = key.hash & mask;; index = next(index)) {
        Object k = table[index];

        if (k == key.reference) {
            // Replace existing entry.
            table[index + 1] = value;
            return;
        }

        if (k == null) {
            if (firstTombstone == -1) {
                // Fill in null slot.
                table[index] = key.reference;
                table[index + 1] = value;
                size++;
                return;
            }

            // Go back and replace first tombstone.
            table[firstTombstone] = key.reference;
            table[firstTombstone + 1] = value;
            tombstones--;
            size++;
            return;
        }

        // Remember first tombstone.
        if (firstTombstone == -1 && k == TOMBSTONE) {
            firstTombstone = index;
        }
    }
}

我们不需要知道上面代码中的具体算法,但是从上面的代码中可以得到一个ThreadLocal对象保存数据规则:
通过调用ThreadLocal对象的set方法最终将ThreadLocal对象的reference和数据保存到了values的成员变量table中,并且ThreadLocal对象的reference保存位置总是在数据的前一个位置。

接下来我们来看一下ThreadLocal获取数据的get方法:

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

通过上面对ThreadLocal保存数据的set方法的分析,ThreadLocal获取数据的get方法的逻辑就比较清晰了,首先获取执行get方法线程实例的成员变量localValues的值并且赋值给values;如果values不为null,先获取到ThreadLocal对象的reference在table数组中的位置,然后返回table数组的下一个位置(table数组中数据的位置)的值,如果values为null,就会返回初始值,初始值是在ThreadLocal的initialValue方法中定义的,默认值为null:

protected T initialValue() {
    return null;
}

通过上面对ThreadLocal的set和get方法分析中可以看出,ThreadLocal对象通过set 方法保存数据或者通过get方法获取数据最终操作的是当前线程实例中的成员变量localValues的成员变量table数组,因此可以证明上面结论中的前两条,又由于ThreadLocal.Values的构造方法中table数值被初始化为长度为32的数值,因此一个线程中最多保存16个数据,从而证明上面结论中的第3条。

源码分析

Handler机制其实就是Handler、消息队列(MessageQueue)、消息循环(Looper)三者之间的工作机制,顾名思义消息队列主要负责存放发送过来的消息(即消息的插入)和获取消息,获取消息的同时会删除消息;消息循环主要负责不断从消息队列中获取消息并且将获取到的消息交给Handler处理;Handler主要负责向消息队列发送消息和处理消息循环获取的消息。

Handler机制包含创建消息循环、发送消息和处理消息三个流程,下面会分别分析每个流程。

1 创建消息循环的流程

只有在创建具有消息循环的工作线程时我们才需要了解创建消息循环的流程,Handler机制中创建消息循环的流程通过下面的模板代码可以实现:

new Thread(new Runnable() {
    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
            }
        };
        Looper.loop();
    }
}).start();

run方法的3句代码就是用来创建消息循环的,首先我们来看一下Looper类的prepare方法:

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

由上面的代码可知Looper类的prepare方法会先判断当前线程中是否保存了Looper实例,如果已经保存了,就会抛出一个运行时异常,否者就会创建一个Looper实例并且将其保存到当前线程中。上面代码中从当前线程中获取Looper实例和将Looper实例保存到当前线程中都是通过ThreadLocal实现的,关于ThreadLocal可以参考预备知识。
下面我们接着分析Looper实例的创建过程:

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

Looper实例的构造方法是一个私有方法,因此我们只有通过公有的静态方法prepare来间接创建Looper实例,Looper的构造方法一共做了两件事情:
1 创建一个允许退出的MessageQueue的实例(因为代码中传递给MessageQueue构造方法的参数的值为true),并且将其赋值给成员变量mQueue。
2 获取当前线程的实例,并且将其赋值给成员变量mThread。
下面我们接着分析创建一个允许退出的MessageQueue的实例的过程:

MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    mPtr = nativeInit();
}

MessageQueue的构造方法一共做了两件事情:
1 保存允许退出的标记
2 通过调用native层的方法nativeInit来初始化MessageQueue实例。

到此Looper类的prepare方法分析完毕,该方法会创建一个持有一个允许退出的消息队列(即MessageQueue实例)的消息循环(即Looper实例),并且将该Looper实例保存到当前线程中,但是此时的消息循环还没有运行起来。
run方法的第2句代码创建是用来创建一个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());
        }
    }

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

由上面的代码可知,Handler一共做了3件我所关心的事情:
1 获取当前线程中的Looper实例,并且将其赋值给成员变量mLooper,如果当前线程没有Looper实例,就会抛出一个运行时异常,相信这个异常提示大家都见过了,因此run方法的第2句必须在第1句的后面
2 获取Looper实例中的MessageQueue实例,并且将其赋值给成员变量mQueue。
3 成员变量mAsynchronous被设置为false(通常的开发中mAsynchronous不会设置为true)。

run方法的第3句代码是用来驱动消息循环的,我会在处理消息流程中分析Looper类的loop方法是如何驱动消息循环的。

在下面消息处理流程的分析中可以看出在消息循环不退出的情况下run方法第3句代码后面的代码不会被执行,继而run方法的3句代码的顺序必须是上面模板代码中的顺序

到此创建消息队列流程已经分析完毕,创建消息队列流程的关键细节如下:
1 在工作线程中创建的消息循环都是允许退出的,并且当所有的事情都完成以后应该调用消息循环Looper中的quit或者quitSafely方法来退出消息循环,否者线程会一直处于空闲等待状态。
2 创建消息队列的代码顺序是固定的,必须按照上面模板代码的顺序。

2 发送消息流程

先通过如下的流程图,整体的看一下发送消息流程:



由上图可知,Handler发送消息的方式有两种,分别是通过sendMessagexxx(以sendMessage方法为例)方法发送消息和通过postxxx(以post方法为例)方法发送消息,其实这两种方式最终会调用sendMessageDelayed方法来发送消息, 先来看一Handler类的post方法:

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}

可以看到post方法有一个Runnable类型的参数r,getPostMessage方法会创建一个callback为r的Message对象并且将其返回,源码如下:

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

接着post方法会调用sendMessageDelayed方法并且将getPostMessage方法创建的Message对象作为它的第一个参数,第二个参数延迟时间设置为0,表示该消息会被立即处理。我们再来看一下Handler类的sendMessage方法:

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}

sendMessage方法也会调用sendMessageDelayed方法,并且延迟时间也设置为0。
接下来我们就来看一下sendMessageDelayed方法:

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

sendMessageDelayed方法会先判断延迟时间是否小于零,如果小于0,就将延迟时间设置为0,也就是要求消息的处理时间必须在消息发送时间之后,接着就会获取当前时间与延迟时间的和,也就是消息处理的准确时间,最后调用sendMessageAtTime方法并且将消息处理的准确时间作为参数。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);
}

sendMessageAtTime方法最终会调用Handler类的enqueueMessage方法并且将Handler持有的消息队列queue作为参数,Handler类的enqueueMessage方法的源码如下所示:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

Handler类的enqueueMessage方法首先会将消息msg的target设置为当前的Handler实例,最后会调用MessageQueue类的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;
}

由上面的代码可知,MessageQueue类的enqueueMessage方法首先会判断消息队列是否正在退出(mQuitting为true代表消息队列正在退出),如果消息队列正在退出,则返回false,代表发送消息失败,最终post和sendMessage方法也会返回false。在工作线程中如果手动为其创建了消息循环,那么当所有的事情都完成以后应该通过调用Looper类中的quit或者quitSafely方法来退出消息循环,否者工作线程不会终止并且会一直处于空闲等待状态,Looper类中的quit和quitSafely方法源码如下:

public void quit() {
    mQueue.quit(false);
}

public void quitSafely() {
    mQueue.quit(true);
}

可以看到quit和quitSafely方法都会调用MessageQueue类中的quit方法来设置消息队列正在被退出(即设置mQuitting为true),只不过调用MessageQueue类中的quit方法传递的参数分别是false和true(代表是否安全退出消息队列),MessageQueue类的quit方法如下所示:

void quit(boolean safe) {
    if (!mQuitAllowed) {
        throw new IllegalStateException("Main thread not allowed to quit.");
    }

    synchronized (this) {
        if (mQuitting) {
            return;
        }
        mQuitting = true;

        if (safe) {
            removeAllFutureMessagesLocked();
        } else {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}

由上面的代码可知,是否安全退出消息循环的区别在于处理当前消息队列中未处理的消息的方式不同,直接退出消息循环的处理方式对应与MessageQueue 类的removeAllMessagesLocked方法,安全退出消息循环的处理方式对应与MessageQueue 类的removeAllFutureMessagesLocked方法,源码如下:

private void removeAllMessagesLocked() {
    Message p = mMessages;
    while (p != null) {
        Message n = p.next;
        p.recycleUnchecked();
        p = n;
    }
    mMessages = null;
}

private void removeAllFutureMessagesLocked() {
    final long now = SystemClock.uptimeMillis();
    Message p = mMessages;
    if (p != null) {
        if (p.when > now) {
            removeAllMessagesLocked();
        } else {
            Message n;
            for (;;) {
                n = p.next;
                if (n == null) {
                    return;
                }
                if (n.when > now) {
                    break;
                }
                p = n;
            }
            p.next = null;
            do {
                p = n;
                n = p.next;
                p.recycleUnchecked();
            } while (n != null);
        }
    }
}

由上面的代码可知,removeAllMessagesLocked方法会将消息队列中未处理的消息直接销毁掉,而removeAllFutureMessagesLocked方法会将消息队列中比当前时间靠后的消息销毁掉并且将比当前时间靠前的消息正常处理掉;下一节会通过分析得到消息循环的退出条件是调用了Looper的quit/quitSafely方法并且消息队列为空

我们继续分析MessageQueue类的enqueueMessage方法接下来的源码,从代码中可以看出消息队列就是一个按照消息执行时间的先后顺序存放消息的单链表,当此时的消息队列为空或者发送过来的消息执行时间为0或者发送过来的消息执行时间小于消息队列中第一个消息的执行时间时,就将消息作为消息队列的头并且设置needWake为true(代表需要唤醒线程);否者的话,就会遍历整个消息队列,按照时间先后的顺序将消息插入到消息队列中并且设置needWake为false(代表不需要唤醒线程,在1中的Handler实例的创建过程中mAsynchronous被设置为false,导致Handler类的enqueueMessage方法不会将消息设置为异步的,因此needWake = mBlocked && p.target == null && msg.isAsynchronous();这一句代码必会将needWake设置为false),最后如果needWake为true,就会调用JNI方法nativeWake唤醒线程

3 处理消息流程

先通过如下的流程图,整体的看一下处理消息流程:


Handler 处理消息流程

上图中执行的第一个方法就是Looper类的loop方法,因为Looper类的loop方法是用来驱动消息循环的,只有消息循环被驱动的情况下,消息才会被处理,Looper类的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();
    }
}

Looper类的loop方法首先会获取当前线程的Looper实例,如果当前线程没有Looper实例,就会抛出一个运行时异常。接着通过一个无限循环来获取消息队列中需要被处理的消息,这样消息循环就被驱动起来了;无限循环中通过MessageQueue类的next方法来获取即将需要被处理的消息,消息循环退出的唯一条件是MessageQueue类的next方法返回null,MessageQueue类的next方法源码如下(由于源码太长,只展示了关键代码):

Message next() {
    ......
    int nextPollTimeoutMillis = 0;
    for (;;) {
        ......
        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) {
                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;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            ......
        }
        ......
    }
}

上面代码中的nativePollOnce方法是一个JNI方法,该方法是用来使当前线程进入到空闲等待状态,等待时长为传入该方法的第二个参数nextPollTimeoutMillis的值,在此期间可以通过JNI方法nativeWake唤醒该线程或者超时后线程自动会被唤醒;无限for循环开始时传入的值为0,表示不等待;当消息队列的头消息的执行时间比当前时间靠后,就会将消息队列的头消息的执行时间和当前时间的差值保存到nextPollTimeoutMillis变量中,当消息队列中为null时,将-1(-1代表永久处于空闲等待状态)保存到nextPollTimeoutMillis变量中,nextPollTimeoutMillis用来下一次执行nativePollOnce方法时使用。
所以MessageQueue类的next方法返回null只有一种可能:mQuitting的值为true(退出消息循环会将mQuitting的值设置为true)并且消息队列为空

在Looper类的loop方法中,MessageQueue类的next方法获取即将需要被处理的消息后,接着调用消息的target(target就是发送消息的Handler实例,从而间接的说明了消息是被消息所在的Looper实例对应的线程处理的)的dispatchMessage方法来处理消息,Handler类的dispatchMessage方法如下所示:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

上面的代码逻辑很简单,就是Handler处理消息的流程,可以对照上面的Handler 处理消息流程图 进行理解;按照2中sendMessagexxx方法发送的消息最终会被Handler类handleMessage方法处理,按照2中postxxx方法发送的消息最终会被Handler类handleCallback方法处理;如果通过包含Callback接口类型参数的构造方法创建Handler实例,例如public Handler(Callback callback),那么按照2中sendMessagexxx方法发送的消息最终会被Callback接口的handleMessage方法处理。

实例讲解

对于消息循环模型的使用可以分为两种情况:
1> 工作线程向UI线程发送消息
2> UI线程向工作线程发送消息

1 工作线程向UI线程发送消息的常见实现方式有3种,
1> 第一种实现方式的实例代码如下:

mHandler = new Handler(){

   @Override
   public void handleMessage(Message msg) {
       // TODO Auto-generated method stub
       super.handleMessage(msg);
       
       if(1 == msg.what){
           android.util.Log.i(TAG,"msg.what = " + msg.what);
       }
   }
};

new Thread(new Runnable() {
   @Override
   public void run() {
       mHandler.sendEmptyMessage(1);
   }
}).start();

代码逻辑很简单,这里就不再解析了。

2> 有一种简单的方法向UI线程发送消息,就是通过Activity的runOnUiThread方法,该方法的源码如下:

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

该方法实现逻辑很简单,如果当前线程不是UI线程,就通过Handler的post向UI线程发送消息,否者的话,就直接执行action(Runnable类型的实例)的run方法。

3> 由于工作线程向UI线程发送消息的场景在日常开发经常被用到,所以Google为我们提供了HandlerThread类来实现该场景。

2 UI线程向工作线程发送消息的常见实现方式有2种,
1> 第一种实现方式的实例代码如下:

new Thread(new Runnable() {
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Looper.prepare();
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                if(1 == msg.what){
                    android.util.Log.i(TAG,"msg.what = " + msg.what);
                }
            }
        };
        Looper.loop();
    }
}).start();

mHandler.sendEmptyMessage(1);

对上面的代码进行分析:按照一种的模板代码创建消息循环,然后通过mHandler向工作线程发送消息。

2> 由于UI线程向工作线程发送消息的场景在日常开发经常被用到,所以Google为我们提供了AsyncTask类来实现该场景,关于AsyncTask类的使用可以参考Android 线程与进程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容