Handler、Message的简单使用
Handler
extends Object
java.lang.Object | |
↳ | android.os.Handler |
Class Overview
A Handler allows you to send and process Message
and Runnable objects associated with a thread'sMessageQueue
. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
mHandler = new Handler(){public void handleMessage(Message msg){
//int android.os.Message.what
//User-defined message code so that the recipient can identify what this message is about.
switch(msg.what){case UPDATE_TEXT:mTextView.setText("text changed");break;default:break;}}};
public final boolean sendMessage(Message msg)Added inAPI level 1
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received inhandleMessage(Message)
, in the thread attached to this handler.
Returns
- Returns true if the message was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.
Message mMessage = Message.obtain(mHandler, UPDATE_TEXT);//Pushes a message onto the end of the message queue after all pending messages before the current time.
mHandler.sendMessage(mMessage);
2、
Looper
extends Object
java.lang.Object | |
↳ | android.os.Looper |
Class Overview
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, callprepare()
in the thread that is to run the loop, and thenloop()
to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler
class.
Looper时时刻刻监视着MessageQueue,是每个线程中的MessageQueue管家,每个线程中只有一个Looper,调用其loop()方法就会进入到一个无限循环中,每当发现MessageQueue中存在一条消息,就会把它取出,送到Handler中的handleMessage()中。
MessageQueue
extends Object
java.lang.Object | |
↳ | android.os.MessageQueue |
消息队列,每个线程中只会有一个MessageQueue。主要存放所有通过Handler发送的消息。
Message
extends Object
implements Parcelable
java.lang.Object | |
↳ | android.os.Message |
Class Overview
Defines a message containing a description and arbitrary data object that can be sent to aHandler
. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.
//Message android.os.Message.obtain(Handler h, int what)
Message mMessage = Message.obtain(mHandler, UPDATE_TEXT);
Message是在线程之间传递消息,它可以在内部携带少量信息,如what字段、arg1、arg2来携带一些整型数据、obj携带Object对象,用于在不同线程间交换数据。
异步消息处理的整个流程:
Message mMessage = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("key","这里一切安全");
mMessage.what = 0;
mMessage.obj = bundle;
通常会用obtain()方法创建Message,如果消息池中有Message则取出,没有则创建,这样防止对象重复创建,节省资源。
/*** Return a new Message instance from the global pool. Allows us to* avoid allocating new objects in many cases.*/public static Message obtain() {synchronized (sPoolSync) {if (sPool != null) {Message m = sPool;sPool = m.next;m.next = null;sPoolSize--;return m;}}return new Message();}
“铃铃铃……”,小mMessage接到一个店换,"我叫Handler,来此Activity大本营,是你这次任务的接收者,一会我会带你去首都的消息中心去报道。"
mHandler = new Handler(){public void handleMessage(Message msg){
//int android.os.Message.what
//User-defined message code so that the recipient can identify what this message is about.}};
Handler属于Activity,创建任何一个Handler都属于重写了Activity的Handler。
在Handler的构造中,默认完成了对当前线程Looper的绑定。
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;}
通过Looper.myLooper()方法获得当前线程保存的Looper实例,通过Looper.mQueue()获得MessageQueue实例,
static Looper |
myLooper()
Return the Looper object associated with the current thread.
|
static MessageQueue |
myQueue()
Return the
MessageQueue object associated with the current thread.
|
在此时,mHandler实例与looper、messageQueue实例关联上了。
mHandler神情骄傲的对小mMessage说:我已经跟首都的消息中心打好了招呼,准备接收你了,现在有两种车“send”和“post”你想坐哪辆都可以,不过要根据你上司的命令选择对应的型号哦~
final boolean |
post(Runnable r)
Causes the Runnable r to be added to the message queue.
|
final boolean |
postAtFrontOfQueue(Runnable r)
Posts a message to an object that implements Runnable.
|
final boolean |
postAtTime(Runnable r,Object token, long uptimeMillis)
Causes the Runnable r to be added to the message queue, to be run at a specific time given byuptimeMillis.
|
final boolean |
postAtTime(Runnable r, long uptimeMillis)
Causes the Runnable r to be added to the message queue, to be run at a specific time given byuptimeMillis.
|
final boolean |
postDelayed(Runnable r, long delayMillis)
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses
|
final boolean |
sendEmptyMessage(int what)
Sends a Message containing only the what value.
|
final boolean |
sendEmptyMessageAtTime(int what, long uptimeMillis)
Sends a Message containing only the what value, to be delivered at a specific time.
|
final boolean |
sendEmptyMessageDelayed(int what, long delayMillis)
Sends a Message containing only the what value, to be delivered after the specified amount of time elapses.
|
final boolean |
sendMessage(Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time.
|
final boolean |
sendMessageAtFrontOfQueue(Message msg)
Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop.
|
boolean |
sendMessageAtTime(Message msg, long uptimeMillis)
Enqueue a message into the message queue after all pending messages before the absolute time (in milliseconds)uptimeMillis.
|
final boolean |
sendMessageDelayed(Message msg, long delayMillis)
Enqueue a message into the message queue after all pending messages before (current time + delayMillis).
|
String | toString() |
Looper.prepare();
static void |
prepareMainLooper()
Initialize the current thread as a looper, marking it as an application's main looper.
|
Looper的构造方法中,创建了和他一一对应的MessageQueue
private Looper(boolean quitAllowed){mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();
}
在Android中ActivityThread的main方法是程序入口,主线程的Looper和MessageQueue就是在此刻创建。
public static void loop()
Run the message queue in this thread. Be sure to callquit()
to end the loop.
loop()方法有一个for死循环,不断调用queue.next()方法,在消息队列中取出Message。并在Message中取出target,这个target就是发送消息的mHandler调用它的dispatchMessage()方法。
public void dispatchMessage(Message msg){
if(msg.callback != null){
handleCallback.handleMessage(msg);
}else{
if(mCallback != null){
if(mCallback.handleMessage(msg)){
return;}
}
handleMessage(msg);
}
}
dispatchMessage()方法:若mCallback不为空,则调用mCallback的handleMessage();否则,直接调用Handler的handleMessage()方法,并将消息对象作为参数传递过去。在handleMessage()方法中,小mMessage出色的完成了任务。
Thanks to MeloDev、stromzhang
Handler、Message的简单使用相关推荐
- 【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )
文章目录 I . Handler 机制简介 II . Handler 机制 Handler Message Looper MessageQueue 四组件对应关系 III . Handler ( 消息 ...
- Android Handler Message 里面的message.what, message.arg1,message.obj,obtainMessage, message.setData的使用
Android Handler Message 里面的message.what, message.arg1,message.arg2,message.obj,obtainMessage, messag ...
- Spring MVC-处理程序映射(Handler Mapping)-简单的Url处理程序映射(Simple Url Handler Mapping)示例(转载实践)...
以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_simpleurlhandlermapping.htm 说明:示例基于Spring ...
- Android -- 消息处理机制源码分析(Looper,Handler,Message)
android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因 ...
- android的消息处理机制(图+源码分析)——Looper,Handler,Message
android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种helper类,对于和我一样渴望水平得到进阶的人来说,都太值得一读了.这不,前几天为了了解android ...
- 【转】android的消息处理机制(图+源码分析)——Looper,Handler,Message
原文地址:http://www.cnblogs.com/codingmyworld/archive/2011/09/12/2174255.html#!comments 作为一个大三的预备程序员,我学习 ...
- android的消息处理机制(图文+源码分析)—Looper/Handler/Message[转]
from:http://www.jb51.net/article/33514.htm 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设计思想.andro ...
- Android Handler处理机制 ( 三 ) ——Handler,Message,Looper,MessageQueue
在android中提供了一种异步回调机制Handler,使用它,我们可以在完成一个很长时间的任务后做出相应的通知 handler基本使用: 在主线程中,使用handler很简单,new一个Handle ...
- 【Android 异步操作】手写 Handler ( Message 消息 | ThreadLocal 线程本地变量 | Looper 中的消息队列 MessageQueue )
文章目录 一.Message 消息 二.ThreadLocal 线程本地变量 三.Looper 中的消息队列 MessageQueue 一.Message 消息 模仿 Android 中的 Messa ...
最新文章
- 【Data】数据结构之C++程序设计(1)
- Code Sign error: Provisioning profile 'xxxxxxxxxxxxxxxxxxxxxxxxx'
- 新发现为类脑计算机开辟了道路
- HTML控制文本框只能输入数字和小数点,并且只能保留小数点后两位 金额转换,阿拉伯数字的金额转换成 面试题
- 论文笔记:Integrating Classification and Association Rule Mining (即,CBA算法介绍)
- 计组第一章(唐朔飞)——计算机系统概述章节总结
- 洛谷P1061 Jam的计数法
- Unity3D-RayMarch-几何图元1-添加基本着色模型
- 同学孩子上985大学,每月生活费5000元,大家认为合适吗?
- Matlab Tricks(十四)—— 某一行/列是否在一个矩阵中(ismember)
- 正斜杠“/”与反斜杠”\”
- Docker学习之docker常用命令
- 接口交互时的URL带有日期格式的参数,注意拼装地址中的特殊符号(如空格等)
- 夜深人静写算法【递归】
- java 鸡尾酒排序_java交换排序之鸡尾酒排序实现方法
- 建立数据驱动,关键字驱动和混合Selenium框架这些你了解吗
- 一种增加图像自然饱和度的方法
- 内存地址对齐问题研究所分析
- Linux对大于2T的磁盘分区方法及创建逻辑卷LVM
- Mandatory condition is missing
热门文章
- 超越JUnit –测试框架的替代方案
- 运行时vs编译时类路径
- LFS、BLFS、ALFS、HLFS的区别详解
- tomcat服务器通过配置来部署程序
- python判断奇偶数字符串的拼接_Python字符串拼接方法总结
- 在c语言中char型数据在内存中的储存形式为什么
- C语言没有引用,只有指针
- python get()函数_C++使用ffpython嵌入和扩展python(python2和python3)
- matlab resample,resample matlab实现
- 净迁移人口预测程序python_高质量深度学习模型, 一键模型预测,迁移学习很简单...