讲义摘录之26: 活用Android 的Message Queue(1/3)
1. Message Queue 的角色
(1)在你的Android 程序里,新创建一个线程,或称执行绪(Thread)时,并不会自动建立其
Message Loop 。
(2 )Android 里并没有Global 的Message Queue 数据结构,例如,不同APK 里的对象不能通过
Massage Queue 来交换消息(Message) 。
(3 )一个线程可以创建一个Looper 对象,由它来管理此线程里的Message Queue 。
(4 )你可以创建Handler 对象来与Looper 沟通,以便push 新消息到Message Queue 里;或者
接收Looper(从Message Queue 取出)所送来的消息。
(5 )线程A 的Handler 对象引用可以传递给其他线程,让其他线程B 或C 等能发送消息给线
程A(存于A 的Message Queue 里) 。
(6 )线程A 的Message Queue 里的消息,只有线程A 所属的对象可以处理之。
(7 )使用Looper.myLooper 可以取得当前线程的Looper 对象引用值。
(8 )使用mHandler = new EevntHandler(Looper.myLooper ()); 可创建用来处理当前线程的
Handler 对象;其中,EevntHandler 是Handler 的子类。
(9 )使用mHandler = new EevntHandler(Looper.getMainLooper ()); 可创建用来处理main 线程的
Handler 对象;其中,EevntHandler 是Handler 的子类别。
2. 范例之一:Looper 对象的角色
Looper 类用来管理特定线程内对象之间的消息交换(Message Exchange) 。你的应用程序可以
创建许多个线程,或称执行线程(Thread) 。而一个线程可以创建许多个对象,这些对象之间常常
需要互相交换消息。如果有这种需要,您可以替线程创建一个Looper 对象,来担任消息交换的
管理工作。Looper 对象会建立一个MessageQueue 数据结构来存放各对象传来的消息(包括UI 事
件或System 事件等) 。如下图:
作用:
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.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
每一个线程(Thread,或称「执行绪」)里