Android消息处理的大致的原理如下:

  1.有一个消息队列,可以往队列中添加消息

  2.有一个消息循环,可以从消息队列中取出消息

Android系统中这些工作主要由Looper和Handler两个类来实现:

  Looper类: 有一个消息队列,封装消息循环

  Handler类: 消息的投递、消息的处理

Looper类:

  Looper的使用需先调用 Looper.prepare(),然后调用Looper.loop()开启消息循环。

     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));
}     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

  prepare会在调用线程的局部变量中设置一个Looper对象;

  ThreadLocal是java中线程局部变量类,有两个关键函数:

      set: 设置调用线程的局部变量

      get: 获取调用线程的局部变量

  Looper的构造函数:  

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

  创建了一个消息队列,用于存放消息。

  Looper.loop(), myLooper()通过ThreadLocal对象获取了prepare时创建的Looper对象。loop里面是一个循环,循环从MessageQueue中取消息,然后通过Handler去处理。

  (msg.target.dispatchMessage(msg); target是一个Handler对象,后面会提到)

     public static @Nullable Looper myLooper() {
return sThreadLocal.get();
} 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的作用:

  • 封装一个消息队列

  • prepare()方法把Looper对象和调用的线程绑定起来

  • 通过loop()方法处理消息队列中的消息    

Hander类:

  Handler有多个构造函数,常用的就下面几个:     

     public Handler() {
this(null, false);
} public Handler(Looper looper) {
this(looper, null, false);
} 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;
} public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

  无参构造函数,通过Looper.myLooper()获取调用线程的Looper对象; Handler提供了一个Callback的接口,参数里面的Callback在处理消息的时候会用到,如果设置了全局Callback,消息会通过这个Callback处理,如果未设置,则需重重载handlerMessage()方法来处理消息。

     public interface Callback {
public boolean handleMessage(Message msg);
}

  (1) Handler和Message ----> Handler把Message插入Looper的消息队列。

    Handler有一系列的处理消息的函数,比如:     

     public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
} 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);
} public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}

   这些都是将消息插入到Looper的消息队列,sendMessageAtFrontOfQueue()是将消息插入到消息队列的队列头,所以优先级很高。所有方法最后都是通过enqueueMessage()方法插入消息。

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

    msg.target = this,前面有提到,target是Handler对象,消息的处理最后都需通过这个。

  (2)Handler的消息处理

    上面的Looper.loop()方法中,不断从消息队列中提取消息,然后通过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设置了callback,则通过这个callback处理,如果Message没设置callback则先通过全局callback来处理,如果都没设置,则通过handlerMessage()方法来处理。

  简单总结一下:

    Looper中有一个MessageQueue,里面存储一个个待处理的Message。

    Message中有一个Handler,这个Handler处理Message。

    转载还望注明出处:http://www.cnblogs.com/xiaojianli/p/5642380.html

Looper Handler MessageQueue Message 探究的更多相关文章

  1. Android开发之漫漫长途 ⅥI——Android消息机制(Looper Handler MessageQueue Message)

    该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...

  2. Android开发之漫漫长途 Ⅶ——Android消息机制(Looper Handler MessageQueue Message)

    该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...

  3. android的消息处理有三个核心类:Looper,Handler和Message。

    android的消息处理机制(图+源码分析)——Looper,Handler,Message   作为 一名android程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设 ...

  4. Looper: Looper,Handler,MessageQueue三者之间的联系

    在Android中每个应用的UI线程是被保护的,不能在UI线程中进行耗时的操作,其他的子线程也不能直接进行UI操作.为了达到这个目的Android设计了handler Looper这个系统框架,And ...

  5. Looper,Handler, MessageQueue

    Looper Looper是线程用来运行消息循环(message loop)的类.默认情况下,线程并没有与之关联的Looper,可以通过在线程中调用Looper.prepare() 方法来获取,并通过 ...

  6. android的消息处理机制——Looper,Handler,Message

    在开始讨论android的消息处理机制前,先来谈谈一些基本相关的术语. 通信的同步(Synchronous):指向客户端发送请求后,必须要在服务端有回应后客户端才继续发送其它的请求,所以这时所有请求将 ...

  7. 转 Android的消息处理机制(图+源码分析)——Looper,Handler,Message

    作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设计思想.android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种 ...

  8. 【转】android的消息处理机制(图+源码分析)——Looper,Handler,Message

    原文地址:http://www.cnblogs.com/codingmyworld/archive/2011/09/12/2174255.html#!comments 作为一个大三的预备程序员,我学习 ...

  9. android的消息处理机制(图+源码分析)——Looper,Handler,Message

    android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种helper类,对于和我一样渴望水平得到进阶的人来说,都太值得一读了.这不,前几天为了了解android ...

随机推荐

  1. 【BZOJ1036】 树的统计Count (树链剖分)

    Description 一棵树上有n个节点,编号分别为1到n,每个节点都有一个权值w.我们将以下面的形式来要求你对这棵树完成一些操作: I. CHANGE u t : 把结点u的权值改为t II. Q ...

  2. java中的信号量Semaphore

    Semaphore(信号量)充当了操作系统概念下的“信号量”.它提供了“临界区中可用资源信号量”的相同功能.以一个停车场运作为例.为了简单起见,假设停车场只有三个车位,一开始三个车位都是空的.这时如果 ...

  3. Node.js权威指南 (4) - 模块与npm包管理工具

    4.1 核心模块与文件模块 / 574.2 从模块外部访问模块内的成员 / 58 4.2.1 使用exports对象 / 58 4.2.2 将模块定义为类 / 58 4.2.3 为模块类定义类变量或类 ...

  4. 开发备必:WEB前端开发规范文档

    为提高团队协作效率, 便于后台人员添加功能及前端后期优化维护, 输出高质量的文档, 特制订此文档. 本规范文档一经确认, 前端开发人员必 须按本文档规范进行前台页面开发. 本文档如有不对或者不合适的地 ...

  5. 【转】使用unity3d需要注意到细节

    原 文:http://cache.baiducontent.com /c?m=9d78d513d9841df41ea6837e7c01a6660e20f6743da7c76508c3e34f84152 ...

  6. NOI题库05 派

    05:派 Description 我的生日要到了!根据习俗,我需要将一些派分给大家.我有N个不同口味.不同大小的派.有F个朋友会来参加我的派对,每个人会拿到一块派(必须一个派的一块,不能由几个派的小块 ...

  7. Centos 6.4 openNebula4

    我们实验室的 OpenNebula 3.2 已经很稳定的运行了两年,除了开头一个月不熟悉这套云计算软件有点乱.容易犯错外接下来的时间里都很稳定,期间还包括一次防火演习(突然拉闸似断电)和安全检查(计划 ...

  8. Scrambled Polygon - POJ 2007(求凸包)

    给一些点,这些点都是一个凸包上的顶点,以第一个点为起点顺时针把别的点拍排一下序列. 分析:最简单的极坐标排序了..................... 代码如下: ----------------- ...

  9. Div 3 - SGU 105(找规律)

    分析:很容易知道序列1,2,3, 4,5, 6......与3的关系就是1,2, 0,1, 2,0,......如果是在一个数后面添加一个数就变成了这种序列1, 0, 0, 1, 0, 0, 1, 0 ...

  10. 层层递进Struts1(七)详解DispatchAction

    通过前面几篇博客,不知道大家有没有发现这个问题,虽然现在可以灵活控制跳转了,但是Action的数量还是比较多,如何既能保证跳转灵活,还能减少Action的数量?这就是我们这篇博客所说的Dispatch ...