Android通過Looper、Handler來實現消息循環機制,Android消息循環是針對線程的(每個線程都可以有自己的消息隊列和消息循環)。
Android系統中,Looper負責管理線程的消息隊列和消息循環。我們可以通過Loop.myLooper()得到當前線程的Looper對象,通過Loop.getMainLooper()可以獲得當前進程的主線程的Looper對象。
一個線程可以存在(當然也可以不存在)一個消息隊列和一個消息循環(Looper)。
Activity是一個UI線程,運行於主線程中,Android系統在啓動的時候會爲Activity創建一個消息隊列和消息循環(Looper)。
Handler的作用是把消息加入特定的(Looper)消息隊列中,並分發和處理該消息隊列中的消息。構造Handler的時候可以指定一個Looper對象,如果不指定則利用當前線程的Looper創建。
Activity、Looper、Handler,Thread的關係如下圖所示:
一個Activity中可以創建多個工作線程或者其他的組件,如果這些線程或者組件把他們的消息放入Activity的主線程消息隊列,那麼該消息就會在主線程中處理了。
因爲主線程一般負責界面的更新操作,並且Android系統中的widget不是線程安全的,所以這種方式可以很好的實現Android界面更新。在Android系統中這種方式有着廣泛的運用。
那麼一個線程怎樣把消息放入主線程的消息隊列呢?答案是通過Handle對象,只要Handler對象以主線程的Looper創建,那麼調用Handler的sendMessage等接口,將會把消息放入隊列都將是放入主線程的消息隊列。並且將會在Handler主線程中調用該handler的handleMessage接口來處理消息。
更多Android消息隊列的信息請參看: http://my.unix-center.net/~Simon_fu/?p=652
下面這個圖從另外一個角度描述了他們的關係:
轉載自:http://www.oschina.net/question/4873_19701
概述:Android使用消息機制實現線程間的通信,線程通過Looper建立自己的消息循環,MessageQueue是FIFO的消息隊列,Looper負責從MessageQueue中取出消息,並且分發到消息指定目標Handler對象。Handler對象綁定到線程的局部變量Looper,封裝了發送消息和處理消息的接口。
例子:在介紹原理之前,我們先介紹Android線程通訊的一個例子,這個例子實現點擊按鈕之後從主線程發送消息"hello"到另外一個名爲” CustomThread”的線程。
LooperThreadActivity.java
03 |
import
android.app.Activity; |
04 |
import
android.os.Bundle; |
05 |
import
android.os.Handler; |
06 |
import
android.os.Looper; |
07 |
import
android.os.Message; |
08 |
import
android.util.Log; |
09 |
import
android.view.View; |
10 |
import
android.view.View.OnClickListener; |
12 |
public
class LooperThreadActivity extends Activity{
|
13 |
/** Called when the activity is first created. */ |
15 |
private final
int MSG_HELLO =
0 ; |
16 |
private Handler mHandler;
|
19 |
public void
onCreate(Bundle savedInstanceState) { |
20 |
super .onCreate(savedInstanceState); |
21 |
setContentView(R.layout.main); |
22 |
new CustomThread().start(); |
24 |
findViewById(R.id.send_btn).setOnClickListener( new OnClickListener() {
|
27 |
public void
onClick(View v) { |
29 |
Log.d( "Test" , "MainThread is ready to send msg:"
+ str); |
30 |
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget(); |
41 |
class CustomThread
extends Thread {
|
46 |
mHandler = new
Handler(){ |
47 |
public void
handleMessage (Message msg) { |
50 |
Log.d( "Test" , "CustomThread receive msg:"
+ (String) msg.obj); |
main.xml
01 |
<? xml version = "1.0" encoding = "utf-8" ?> |
02 |
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 |
android:orientation = "vertical" |
04 |
android:layout_width = "fill_parent" |
05 |
android:layout_height = "fill_parent" |
08 |
android:layout_width = "fill_parent" |
09 |
android:layout_height = "wrap_content" |
10 |
android:text = "@string/hello" |
12 |
< Button android:text = "發送消息" android:id = "@+id/send_btn" android:layout_width = "wrap_content" android:layout_height = "wrap_content" ></ Button > |
Log打印結果:
原理:
我們看到,爲一個線程建立消息循環有四個步驟:
1、 初始化Looper
2、 綁定handler到CustomThread實例的Looper對象
3、 定義處理消息的方法
4、 啓動消息循環
下面我們以這個例子爲線索,深入Android源代碼,說明Android Framework是如何建立消息循環,並對消息進行分發的。
1、 初始化Looper : Looper.prepare()
Looper.java
1 |
private
static final ThreadLocal sThreadLocal = new
ThreadLocal(); |
2 |
public
static final
void prepare() { |
3 |
if (sThreadLocal.get() !=
null ) { |
4 |
throw new
RuntimeException( "Only one Looper may be created per thread" ); |
6 |
sThreadLocal.set( new Looper());
|
一個線程在調用Looper的靜態方法prepare()時,這個線程會新建一個Looper對象,並放入到線程的局部變量中,而這個變量是不和其他線程共享的(關於ThreadLocal的介紹)。下面我們看看Looper()這個構造函數:
Looper.java
1 |
final
MessageQueue mQueue; |
3 |
mQueue = new
MessageQueue(); |
5 |
mThread = Thread.currentThread(); |
可以看到在Looper的構造函數中,創建了一個消息隊列對象mQueue,此時,調用Looper. prepare()的線程就建立起一個消息循環的對象(此時還沒開始進行消息循環)。
2、 綁定handler到CustomThread實例的Looper對象 : mHandler= new Handler()
Handler.java
01 |
final
MessageQueue mQueue; |
04 |
if (FIND_POTENTIAL_LEAKS) {
|
05 |
final Class<?
extends Handler> klass = getClass();
|
06 |
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && |
07 |
(klass.getModifiers() & Modifier.STATIC) == 0 ) {
|
08 |
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
|
09 |
klass.getCanonicalName()); |
13 |
mLooper = Looper.myLooper(); |
15 |
throw new
RuntimeException( |
16 |
"Can't create handler inside thread that has not called Looper.prepare()" ); |
18 |
mQueue = mLooper.mQueue; |
Handler通過mLooper = Looper.myLooper();綁定到線程的局部變量Looper上去,同時Handler通過mQueue =mLooper.mQueue;獲得線程的消息隊列。此時,Handler就綁定到創建此Handler對象的線程的消息隊列上了。
3、定義處理消息的方法:Override public void handleMessage (Message msg){} 子類需要覆蓋這個方法,實現接受到消息後的處理方法。
4、啓動消息循環 : Looper.loop()
所有準備工作都準備好了,是時候啓動消息循環了!Looper的靜態方法loop()實現了消息循環。
Looper.java
01 |
public
static final
void loop() { |
02 |
Looper me = myLooper(); |
03 |
MessageQueue queue = me.mQueue; |
07 |
Binder.clearCallingIdentity(); |
08 |
final long
ident = Binder.clearCallingIdentity(); |
11 |
Message msg = queue.next(); |
16 |
if (msg.target ==
null ) { |
20 |
if (me.mLogging!=
null ) me.mLogging.println( |
21 |
">>>>> Dispatching to " + msg.target +
" " |
22 |
+ msg.callback + ": "
+ msg.what |
24 |
msg.target.dispatchMessage(msg); |
25 |
if (me.mLogging!=
null ) me.mLogging.println( |
26 |
"<<<<< Finished to " + msg.target +
" " |
31 |
final long
newIdent = Binder.clearCallingIdentity(); |
32 |
if (ident != newIdent) {
|
33 |
Log.wtf( "Looper" , "Thread identity changed from 0x" |
34 |
+ Long.toHexString(ident) + " to 0x" |
35 |
+ Long.toHexString(newIdent) + " while dispatching to " |
36 |
+ msg.target.getClass().getName() + " " |
37 |
+ msg.callback + " what="
+ msg.what); |
while(true)體現了消息循環中的“循環“,Looper會在循環體中調用queue.next()獲取消息隊列中需要處理的下一條消息。當msg != null且msg.target != null時,調用msg.target.dispatchMessage(msg);分發消息,當分發完成後,調用msg.recycle();回收消息。
msg.target是一個handler對象,表示需要處理這個消息的handler對象。Handler的void dispatchMessage(Message msg)方法如下:
Handler.java
01 |
public
void dispatchMessage(Message msg) { |
02 |
if (msg.callback !=
null ) { |
05 |
if (mCallback !=
null ) { |
06 |
if (mCallback.handleMessage(msg)) {
|
可見,當msg.callback== null 並且mCallback == null時,這個例子是由handleMessage(msg);處理消息,上面我們說到子類覆蓋這個方法可以實現消息的具體處理過程。
總結:從上面的分析過程可知,消息循環的核心是Looper,Looper持有消息隊列MessageQueue對象,一個線程可以把Looper設爲該線程的局部變量,這就相當於這個線程建立了一個對應的消息隊列。Handler的作用就是封裝發送消息和處理消息的過程,讓其他線程只需要操作Handler就可以發消息給創建Handler的線程。由此可以知道,在上一篇《Android異步處理一:使用Thread+Handler實現非UI線程更新UI界面》中,UI線程在創建的時候就建立了消息循環(在ActivityThread的public
static final void main(String[] args)方法中實現),因此我們可以在其他線程給UI線程的handler發送消息,達到更新UI的目的。
文章轉自:http://blog.csdn.net/mylzc/article/details/6771331