1.Android-Looper类
Android中的Looper类,是用来封装消息循环和消息队列的一个类,用于在android线程中进行消息处理。handler其实可以看做是一个工具类,用来向消息队列中插入消息的。
(1) Looper类用来为一个线程开启一个消息循环。
默认情况下android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。)
Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
(2) 通常是通过Handler对象来与Looper进行交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。
默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。
mainHandler = new Handler() 等价于new Handler(Looper.myLooper().
Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。
(3) 在非主线程中直接new Handler() 会报如下的错误:
E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。
(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。
注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。
(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。
把下面例子中的mHandler声明成类成员,在主线程通过mHandler发送消息即可。
Android官方文档中Looper的介绍:
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, call prepare() in the thread that is to run
the loop, and then loop() to have it process messages until the loop is stopped.Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
classLooperThread extendsThread {
publicHandler mHandler;
publicvoid run() {
Looper.prepare();
mHandler = newHandler() {
publicvoid handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
2.消息循环与Looper的详解
本篇文章是对Android中消息循环与Looper的应用进行了详细的分析介绍,需要的朋友参考下
Understanding Looper
Looper是用于给一个线程添加一个消息队列(MessageQueue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止。通常情况下不会用到Looper,因为对于Activity,Service等系统组件,Frameworks已经为我们初始化好了线程(俗称的UI线程或主线程),在其内含有一个Looper,和由Looper创建的消息队列,所以主线程会一直运行,处理用户事件,直到某些事件(BACK)退出。
如果,我们需要新建一个线程,并且这个线程要能够循环处理其他线程发来的消息事件,或者需要长期与其他线程进行复杂的交互,这时就需要用到Looper来给线程建立消息队列。
使用Looper也非常的简单,它的方法比较少,最主要的有四个:
public static prepare();
public static myLooper();
public static loop();
public void quit();
使用方法如下:
1. 在每个线程的run()方法中的最开始调用Looper.prepare(),这是为线程初始化消息队列。
2. 之后调用Looper.myLooper()获取此Looper对象的引用。这不是必须的,但是如果你需要保存Looper对象的话,一定要在prepare()之后,否则调用在此对象上的方法不一定有效果,如looper.quit()就不会退出。
3. 在run()方法中添加Handler来处理消息
4. 添加Looper.loop()调用,这是让线程的消息队列开始运行,可以接收消息了。
5. 在想要退出消息循环时,调用Looper.quit()注意,这个方法是要在对象上面调用,很明显,用对象的意思就是要退出具体哪个Looper。如果run()中无其他操作,线程也将终止运行。
下面来看一个实例
这个例子实现了一个执行任务的服务,主线程和子线程相互通信
public class LooperDemoActivity extends Activity { private WorkerThread mWorkerThread; private TextView mStatusLine; private Handler mMainHandler; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.looper_demo_activity); mMainHandler = new Handler() { @Override public void handleMessage(Message msg) { String text = (String) msg.obj; if (TextUtils.isEmpty(text)) { return; } mStatusLine.setText(text); } }; mWorkerThread = new WorkerThread(); final Button action = (Button) findViewById(R.id.looper_demo_action); action.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mWorkerThread.executeTask("please do me a favor"); } }); final Button end = (Button) findViewById(R.id.looper_demo_quit); end.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mWorkerThread.exit(); } }); mStatusLine = (TextView) findViewById(R.id.looper_demo_displayer); mStatusLine.setText("Press 'do me a favor' to execute a task, press 'end of service' to stop looper thread"); } @Override public void onDestroy() { super.onDestroy(); mWorkerThread.exit(); mWorkerThread = null; } private class WorkerThread extends Thread { protected static final String TAG = "WorkerThread"; private Handler mHandler; private Looper mLooper; public WorkerThread() { start(); } public void run() { /* * Attention: if you obtain looper before Looper#prepare(), you can still use the looper * to process message even after you call Looper#quit(), which means the looper does not * really quit. */ Looper.prepare(); /* * So we should call Looper#myLooper() after Looper#prepare(). Anyway, we should put all stuff between Looper#prepare() * and Looper#loop(). * In this case, you will receive "Handler{4051e4a0} sending message to a Handler on a dead thread * 05-09 08:37:52.118: W/MessageQueue(436): java.lang.RuntimeException: Handler{4051e4a0} sending message * to a Handler on a dead thread", when try to send a message to a looper which Looper#quit() had called, * because the thread attaching the Looper and Handler dies once Looper#quit() gets called. */ mLooper = Looper.myLooper(); // either new Handler() and new Handler(mLooper) will work mHandler = new Handler(mLooper) { @Override public void handleMessage(Message msg) { /* * Attention: object Message is not reusable, you must obtain a new one for each time you want to use it. * Otherwise you got "android.util.AndroidRuntimeException: { what=1000 when=-15ms obj=it is my please * to serve you, please be patient to wait!........ } This message is already in use." */ // Message newMsg = Message.obtain(); StringBuilder sb = new StringBuilder(); sb.append("it is my please to serve you, please be patient to wait!\n"); Log.e(TAG, "workerthread, it is my please to serve you, please be patient to wait!"); for (int i = 1; i < 100; i++) { sb.append("."); Message newMsg = Message.obtain(); newMsg.obj = sb.toString(); mMainHandler.sendMessage(newMsg); Log.e(TAG, "workthread, working" + sb.toString()); SystemClock.sleep(100); } Log.e(TAG, "workerthread, your work is done."); sb.append("\nyour work is done"); Message newMsg = Message.obtain(); newMsg.obj = sb.toString(); mMainHandler.sendMessage(newMsg); }}; Looper.loop(); } public void exit() { if (mLooper != null) { mLooper.quit(); mLooper = null; } }
这个实例中,主线程中执行任务仅是给服务线程发一个消息同时把相关数据传过去,数据会打包成消息对象(Message),然后放到服务线程的消息队列中,主线程的调用返回, 此过程很快,所以不会阻塞主线程。服务线程每当有消息进入消息队列后就会被唤醒从队列中取出消息,然后执行任务。服务线程可以接收任意数量的任务,也即主线程可以 不停的发送消息给服务线程,这些消息都会被放进消息队列中,服务线程会一个接着一个的执行它们----直到所有的任务都完成(消息队列为空,已无其他消息),服务线程会再 次进入休眠状态----直到有新的消息到来。
如果想要终止服务线程,在mLooper对象上调用quit(),就会退出消息循环,因为线程无其他操作,所以整个线程也会终止。
需要注意的是当一个线程的消息循环已经退出后,不能再给其发送消息,否则会有异常抛出"RuntimeException: Handler{4051e4a0} sending message to a Handler on a dead thread"。所以,建议在Looper.prepare()后,调用Looper.myLooper()来获取对此Looper的引用,一来是用于终止(quit()必须在对象上面调用); 另外就是用于接收消息时检查消息循环是否已经退出(如上例)。
3.android的消息处理机制(图文+源码分析)—Looper/Handler/Message
这篇文章写的非常好,深入浅出,关键还是一位大三学生自己剖析的心得。这是我喜欢此文的原因。下面请看正文:
作为一个大三的预备程序员,我学习Android的一大乐趣是可以通过源码学习google大牛们的设计思想。android源码中包含了大量的设 计模式,除此以外,android sdk还精心为我们设计了各种helper类,对于和我一样渴望水平得到进阶的人来说,都太值得一读了。这不,前几天为了了解android的消息处理机 制,我看了Looper,Handler,Message这几个类的源码,结果又一次被googler的设计震撼了,特与大家分享。
android的消息处理有三个核心类:Looper,Handler和Message。其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因此我没将其作为核心类。下面一一介绍:
线程的魔法师 LooperLooper的字面意思是“循环者”,它被设计用来使一个普通线程变成Looper线程。所谓Looper线程就是循环工作的线程。在程序开发中(尤其是GUI开发中),我们经常会需要一个线程不断循环,一旦有新任务则执行,执行完继续等待下一个任务,这就是Looper线程。使用Looper类创建Looper线程很简单:
publicclass LooperThread extends Thread {
@Override
publicvoid run() {
// 将当前线程初始化为Looper线程
Looper.prepare();
// ...其他处理,如实例化handler
// 开始循环处理消息队列
Looper.loop();
}
}
通过上面两行核心代码,你的线程就升级为Looper线程了!!!是不是很神奇?让我们放慢镜头,看看这两行代码各自做了什么。
1)Looper.prepare()
通过上图可以看到,现在你的线程中有一个Looper对象,它的内部维护了一个消息队列MQ。注意,一个Thread只能有一个Looper对象,为什么呢?咱们来看源码。
publicclass Looper {
// 每个线程中的Looper对象其实是一个ThreadLocal,即线程本地存储(TLS)对象
private static final ThreadLocal sThreadLocal =new ThreadLocal();
// Looper内的消息队列
final MessageQueue mQueue;
// 当前线程
Thread mThread;
// 。。。其他属性
// 每个Looper对象中有它的消息队列,和它所属的线程
private Looper() {
mQueue =new MessageQueue();
mRun =true;
mThread = Thread.currentThread();
}
// 我们调用该方法会在调用线程的TLS中创建Looper对象
public static final void prepare() {
if (sThreadLocal.get() !=null) {
// 试图在有Looper的线程中再次创建Looper将抛出异常
thrownew RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
// 其他方法
}
通过源码,prepare()背后的工作方式一目了然,其核心就是将looper对象定义为ThreadLocal。如果你还不清楚什么是ThreadLocal,请参考《理解ThreadLocal》。
2)Looper.loop()
调用loop方法后,Looper线程就开始真正工作了,它不断从自己的MQ中取出队头的消息(也叫任务)执行。其源码分析如下:
publicstaticfinalvoid loop() {
Looper me = myLooper(); //得到当前线程Looper
MessageQueue queue = me.mQueue; //得到当前looper的MQ
// 这两行没看懂= = 不过不影响理解
Binder.clearCallingIdentity();
finallong ident = Binder.clearCallingIdentity();
// 开始循环
while (true) {
Message msg = queue.next(); // 取出message
if (msg !=null) {
if (msg.target ==null) {
// message没有target为结束信号,退出循环
return;
}
// 日志。。。
if (me.mLogging!=null) me.mLogging.println(
">>>>> Dispatching to "+ msg.target +""
+ msg.callback +": "+ msg.what
);
// 非常重要!将真正的处理工作交给message的target,即后面要讲的handler
msg.target.dispatchMessage(msg);
// 还是日志。。。
if (me.mLogging!=null) me.mLogging.println(
"<<<<< Finished to "+ msg.target +""
+ msg.callback);
// 下面没看懂,同样不影响理解
finallong newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf("Looper", "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);
}
// 回收message资源
msg.recycle();
}
}
}
除了prepare()和loop()方法,Looper类还提供了一些有用的方法,比如
Looper.myLooper()得到当前线程looper对象:
publicstaticfinal Looper myLooper() { // 在任意线程调用Looper.myLooper()返回的都是那个线程的looperreturn (Looper)sThreadLocal.get(); }
getThread()得到looper对象所属线程:
public Thread getThread() { return mThread; }
quit()方法结束looper循环:
publicvoid quit() {
// 创建一个空的message,它的target为NULL,表示结束循环消息
Message msg = Message.obtain();
// 发出消息
mQueue.enqueueMessage(msg, 0);
}
到此为止,你应该对Looper有了基本的了解,总结几点:
1.每个线程有且最多只能有一个Looper对象,它是一个ThreadLocal
2.Looper内部有一个消息队列,loop()方法调用后线程开始不断从队列中取出消息执行
3.Looper使一个线程变成Looper线程。
那么,我们如何往MQ上添加消息呢?下面有请Handler!(掌声~~~)
异步处理大师 Handler什么是handler?handler扮演了往MQ上添加消息和处理消息的角色(只处理由自己发出的消息),即通知MQ它要执行一个任务(sendMessage),并在loop到自己的时候执行该任务(handleMessage),整个过程是异步的。handler创建时会关联一个looper,默认的构造方法将关联当前线程的looper,不过这也是可以set的。默认的构造方法:
publicclass handler {
final MessageQueue mQueue; // 关联的MQ
final Looper mLooper; // 关联的looper
final Callback mCallback;
// 其他属性
public Handler() {
// 没看懂,直接略过,,,
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());
}
}
// 默认将关联当前线程的looper
mLooper = Looper.myLooper();
// looper不能为空,即该默认的构造方法只能在looper线程中使用
if (mLooper ==null) {
thrownew RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 重要!!!直接把关联looper的MQ作为自己的MQ,因此它的消息将发送到关联looper的MQ上
mQueue = mLooper.mQueue;
mCallback =null;
}
// 其他方法
}
下面我们就可以为之前的LooperThread类加入Handler:
publicclass LooperThread extends Thread {
private Handler handler1;
private Handler handler2;
@Override
publicvoid run() {
// 将当前线程初始化为Looper线程
Looper.prepare();
// 实例化两个handler
handler1 =new Handler();
handler2 =new Handler();
// 开始循环处理消息队列
Looper.loop();
}
}
加入handler后的效果如下图:
可以看到,一个线程可以有多个Handler,但是只能有一个Looper!
Handler发送消息
有了handler之后,我们就可以使用 post(Runnable)
, postAtTime(Runnable, long)
,postDelayed(Runnable, long)
,sendEmptyMessage(int)
,sendMessage(Message)
, sendMessageAtTime(Message, long)
和sendMessageDelayed(Message, long)
这些方法向MQ上发送消息了。光看这些API你可能会觉得handler能发两种消息,一种是Runnable对象,一种是message对象,这是直观的理解,但其实post发出的Runnable对象最后都被封装成message对象了,见源码:
// 此方法用于向关联的MQ上发送Runnable对象,它的run方法将在handler关联的looper线程中执行
publicfinalboolean post(Runnable r)
{
// 注意getPostMessage(r)将runnable封装成message
return sendMessageDelayed(getPostMessage(r), 0);
}
privatefinal Message getPostMessage(Runnable r) {
Message m = Message.obtain(); //得到空的message
m.callback = r; //将runnable设为message的callback,
return m;
}
publicboolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent =false;
MessageQueue queue = mQueue;
if (queue !=null) {
msg.target =this; // message的target必须设为该handler!
sent = queue.enqueueMessage(msg, uptimeMillis);
}
else {
RuntimeException e =new RuntimeException(
this+" sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
其他方法就不罗列了,总之通过handler发出的message有如下特点:
1.message.target为该handler对象,这确保了looper执行到该message时能找到处理它的handler,即loop()方法中的关键代码
msg.target.dispatchMessage(msg);
2.post发出的message,其callback为Runnable对象
Handler处理消息
说完了消息的发送,再来看下handler如何处理消息。消息的处理是通过核心方法dispatchMessage(Message msg)与钩子方法handleMessage(Message msg)完成的,见源码
// 处理消息,该方法由looper调用
publicvoid dispatchMessage(Message msg) {
if (msg.callback !=null) {
// 如果message设置了callback,即runnable消息,处理callback!
handleCallback(msg);
} else {
// 如果handler本身设置了callback,则执行callback
if (mCallback !=null) {
/* 这种方法允许让activity等来实现Handler.Callback接口,避免了自己编写handler重写handleMessage方法。见http://alex-yang-xiansoftware-com.iteye.com/blog/850865 */
if (mCallback.handleMessage(msg)) {
return;
}
}
// 如果message没有callback,则调用handler的钩子方法handleMessage
handleMessage(msg);
}
}
// 处理runnable消息
privatefinalvoid handleCallback(Message message) {
message.callback.run(); //直接调用run方法!
}
// 由子类实现的钩子方法
publicvoid handleMessage(Message msg) {
}
可以看到,除了handleMessage(Message msg)和Runnable对象的run方法由开发者实现外(实现具体逻辑),handler的内部工作机制对开发者是透明的。这正是handler API设计的精妙之处!
Handler的用处
我在小标题中将handler描述为“异步处理大师”,这归功于Handler拥有下面两个重要的特点:
1.handler可以在任意线程发送消息,这些消息会被添加到关联的MQ上。
2.handler是在它关联的looper线程中处理消息的。
这就解决了android最经典的不能在其他非主线程中更新UI的问题。android的主线程也是一个looper线程(looper 在android中运用很广),我们在其中创建的handler默认将关联主线程MQ。因此,利用handler的一个solution就是在 activity中创建handler并将其引用传递给worker thread,worker thread执行完任务后使用handler发送消息通知activity更新UI。(过程如图)
下面给出sample代码,仅供参考:
publicclass TestDriverActivity extends Activity {
private TextView textview;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textview);
// 创建并启动工作线程
Thread workerThread =new Thread(new SampleTask(new MyHandler()));
workerThread.start();
}
publicvoid appendText(String msg) {
textview.setText(textview.getText() +"\n"+ msg);
}
class MyHandler extends Handler {
@Override
publicvoid handleMessage(Message msg) {
String result = msg.getData().getString("message");
// 更新UI
appendText(result);
}
}
}
publicclass SampleTask implements Runnable {
privatestaticfinal String TAG = SampleTask.class.getSimpleName();
Handler handler;
public SampleTask(Handler handler) {
super();
this.handler = handler;
}
@Override
publicvoid run() {
try { // 模拟执行某项任务,下载等
Thread.sleep(5000);
// 任务完成后通知activity更新UI
Message msg = prepareMessage("task completed!");
// message将被添加到主线程的MQ中
handler.sendMessage(msg);
} catch (InterruptedException e) {
Log.d(TAG, "interrupted!");
}
}
private Message prepareMessage(String str) {
Message result = handler.obtainMessage();
Bundle data =new Bundle();
data.putString("message", str);
result.setData(data);
return result;
}
}
当然,handler能做的远远不仅如此,由于它能post Runnable对象,它还能与Looper配合实现经典的Pipeline Thread(流水线线程)模式。请参考此文《Android Guts: Intro to Loopers and Handlers》 封装任务 Message
在整个消息处理机制中,message又叫task,封装了任务携带的信息和处理该任务的handler。message的用法比较简单,这里不做总结了。但是有这么几点需要注意(待补充):
1.尽管Message有public的默认构造方法,但是你应该通过Message.obtain()来从消息池中获得空消息对象,以节省资源。
2.如果你的message只需要携带简单的int信息,请优先使用Message.arg1和Message.arg2来传递信息,这比用Bundle更省内存
3.擅用message.what来标识信息,以便用不同方式处理message