一、用法。

Looper为了应付新闻周期,在创建过程中初始化MessageQueue。

Handler在一个消息到当前线程的其他线程

MessageQueue用于存储所述消息

Looper其中线程创建的对象。Handler的handleMessage方法就在哪个线程运行

在创建activity时,android系统本身会为activity创建Looper。

final Handler mainHandler = new Handler(getMainLooper())
{
@Override
public void handleMessage(Message msg)
{
String content = "当前线程:" + "msg:" + msg.what;
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
}
};
mainHandler.sendEmptyMessage(0x1);

在其他线程中使用handler消息传递时,必须自己创建looper。以下的样例中HandlerThread封装了Looper和MessageQueue,还实现了获取Looper的同步机制,比較好用。

HandlerThread mThread = new HandlerThread("MyThread");
mThread.start();
Handler mHandle = new Handler(mThread.getLooper())
{
@Override
public void handleMessage(Message msg)
{
String content = "当前线程:" + Thread.currentThread().getName() + "msg:" + msg.what;
System.out.println(content);
}
};
mHandle.sendEmptyMessage(0x2);

二、Looper解析

构造函数:

private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
} 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));
}

在prepare中创建了Looper实例。并在Looper的构造函数中创建了MessageQueue

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
msg.target.dispatchMessage(msg); // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity(); msg.recycle();
}
}

在loop()中。Looper不断的通过queue.next()从MessageQueue取消息,然后调用语句msg.target.dispatchMessage(msg) 来运行。这里target为msg消息的发送者Handler,在分析Handler时再来分析。dispatchMessage在普通情况下会调用Handler类的handleMessage来处理消息。也就是上面样例中我们重载的这个handleMessage。

三、Handler解析

Handler的构造函数有非常多,这里选带Looper參数的构造函数

public Handler(Looper looper) {
this(looper, null, false);
} public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

再看sendMessage。

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) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

sendEmptyMessage将message加到了Looper的MessageQueue中,之后Looper在loop()中调用queue.next()

在enqueueMessage里面。我们看到了msg.target = this

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

假设没有设置Callback的话,就会执行handleMessage了。

四、HandlerThread解析

HandlerThread继承于Thread,对Looper的操作进行了封装,做了同步处理。

public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
} public Looper getLooper() {
if (!isAlive()) {
return null;
} // If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}

handler looper和messageQueue的更多相关文章

  1. Android消息机制探索(Handler,Looper,Message,MessageQueue)

    概览 Android消息机制是Android操作系统中比较重要的一块.具体使用方法在这里不再阐述,可以参考Android的官方开发文档. 消息机制的主要用途有两方面: 1.线程之间的通信.比如在子线程 ...

  2. Handler Looper源码解析(Android消息传递机制)

    Android的Handler类应该是常用到的,多用于线程间的通信,以及子线程发送消息通知UI线程刷新View等等.这里我主要总结下我对整个消息传递机制,包括Handler,Looper,Messag ...

  3. Android消息处理机制(Handler、Looper、MessageQueue与Message)

    Android是消息驱动的,实现消息驱动有几个要素: 消息的表示:Message 消息队列:MessageQueue 消息循环,用于循环取出消息进行处理:Looper 消息处理,消息循环从消息队列中取 ...

  4. (转)Android消息处理机制(Handler、Looper、MessageQueue与Message)

    转自 http://www.cnblogs.com/angeldevil/p/3340644.html Android消息处理机制(Handler.Looper.MessageQueue与Messag ...

  5. 讲讲Handler+Looper+MessageQueue 关系

    Handler+Looper+MessageQueue这三者的关系其实就是Android的消息机制.这块内容相比开发人员都不陌生,在面试中,或者日常开发中都会碰到,今天就来讲这三者的关系. 概述: H ...

  6. Android的消息机制: Message/MessageQueue/Handler/Looper

    概览   * Message:消息.消息里面可包含简单数据.Object和Bundle,还可以包含一个Runnable(实际上可看做回调). * MessageQueue:消息队列,供Looper线程 ...

  7. android学习11——Handler,Looper,MessageQueue工作原理

    Message是Handler接收和处理的消息对象. 每个线程只能拥有一个Looper.它的loop方法读取MessageQueue中的消息,读到消息之后就把消息交给发送该消息的Handler进行处理 ...

  8. Handler,Looper,MessageQueue流程梳理

    目的:handle的出现主要是为了解决线程间通讯. 举个例子,android是不允许在主线程中访问网络,因为这样会阻塞主线程,影响性能,所以访问网络都是放在子线程中执行,对于网络返回的结果则需要显示在 ...

  9. Android 开发 深入理解Handler、Looper、Messagequeue 转载

    转载请注明出处:http://blog.csdn.net/vnanyesheshou/article/details/73484527 本文已授权微信公众号 fanfan程序媛 独家发布 扫一扫文章底 ...

随机推荐

  1. 编译pano13的一些注意事项

    作者:朱金灿 来源:error C2037: "jmpbuf"的左侧部分指定未定义的结构/联合"png_struct_def"e:\src\Test\libpa ...

  2. mac os 虚拟机安装

    https://blog.csdn.net/u011415782/article/details/78505422 感谢

  3. mysql 查询重复 去除重复等等

    查找所有重复标题的记录: SELECT * FROM t_info a WHERE ((SELECT COUNT(*) FROM t_info WHERE Title = a.Title) >  ...

  4. DIKW模型与数据工程(了解)

    DIKW 体系 DIKW体系是关于数据.信息.知识及智慧的体系,可以追溯至托马斯·斯特尔那斯·艾略特所写的诗--<岩石>.在首段,他写道:"我们在哪里丢失了知识中的智慧?又在哪里 ...

  5. NavMesh动态碰撞

    今天遇到一个问题,就是怎样处理一些动态的障碍物. NavMesh是能够躲避静态的障碍物.NavMeshObstacle的作用就是动态添加障碍. 可是有个问题,NavMeshObstacle是圆,连椭圆 ...

  6. 数据局部性(data locality)

    信息处理的典型模式是,将所有数据项视为一个集合,并将其组织为适宜的数据结构(或者说使用适宜的数据结构对之进行存储以及组织),进而借助操作接口高效访问. 为了考查和评价各操作接口的效率,除了从最坏情况的 ...

  7. Html Vedio标签全屏

    http://ask.csdn.net/questions/221701 http://www.zhangxinxu.com/wordpress/2010/03/every-browser-suppo ...

  8. 支付宝开发之手机网站支付(H5支付)

    其实官方的文档中:https://docs.open.alipay.com/203 介绍的已经很详细了,我就实地的看文档操作了一遍,具体步骤如下: 一.创建应用 流程如下: 首先要有支付宝开放平台: ...

  9. 窗体背景的绘制(Windows窗体每次都会重绘其窗体背景,所以我们可以通过拦截窗体重绘背景的消息(WM_ERASEBKGND),并自定义方法来实现重绘窗体背景)

    核心思想:由于Windows窗体每次都会重绘其窗体背景,所以我们可以通过拦截窗体重绘背景的消息(WM_ERASEBKGND),并自定义方法来实现重绘窗体背景.通过TImage组件也可以实现,但是重写W ...

  10. push的时候隐藏底部的tabbar

    push的时候隐藏底部的tabbar #import "mainNavigationControllers.h" @interface mainNavigationControll ...