Android中Message機制的靈活應用

[b]下面我們會以android實例來展示對應的功能,程序界面於下:[/b]
[img]http://www.easyandroid.com/bbs/attachments/month_0909/0909252057c36626e4bbf5b0db.gif[/img]
[b]程序代碼如下,後面部分有代碼說明:[/b]

package com.android.messageexample;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MessageExample extends Activity implements OnClickListener {
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
public TextView tv;
private EventHandler mHandler;
private Handler mOtherThreadHandler=null;
private Button btn, btn2, btn3, btn4, btn5, btn6;
private NoLooperThread noLooerThread = null;
private OwnLooperThread ownLooperThread = null;
private ReceiveMessageThread receiveMessageThread =null;
private Context context = null;
private final String sTag = "MessageExample";
private boolean postRunnable = false;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this.getApplicationContext();
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
btn = new Button(this);
btn.setId(101);
btn.setText("message from main thread self");
btn.setOnClickListener(this);
LinearLayout.LayoutParams param =
new LinearLayout.LayoutParams(250,50);
param.topMargin = 10;
layout.addView(btn, param);
btn2 = new Button(this);
btn2.setId(102);
btn2.setText("message from other thread to main thread");
btn2.setOnClickListener(this);
layout.addView(btn2, param);
btn3 = new Button(this);
btn3.setId(103);
btn3.setText("message to other thread from itself");
btn3.setOnClickListener(this);
layout.addView(btn3, param);
btn4 = new Button(this);
btn4.setId(104);
btn4.setText("message with Runnable as callback from other thread to main thread");
btn4.setOnClickListener(this);
layout.addView(btn4, param);
btn5 = new Button(this);
btn5.setId(105);
btn5.setText("main thread's message to other thread");
btn5.setOnClickListener(this);
layout.addView(btn5, param);
btn6 = new Button(this);
btn6.setId(106);
btn6.setText("exit");
btn6.setOnClickListener(this);
layout.addView(btn6, param);
tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setText("");
LinearLayout.LayoutParams param2 =
new LinearLayout.LayoutParams(FP, WC);
param2.topMargin = 10;
layout.addView(tv, param2);
setContentView(layout);

//主線程要發送消息給other thread, 這裏創建那個other thread
receiveMessageThread = new ReceiveMessageThread();
receiveMessageThread.start();
}

//implement the OnClickListener interface
@Override
public void onClick(View v) {
switch(v.getId()){
case 101:
//主線程發送消息給自己
Looper looper;
looper = Looper.myLooper(); //get the Main looper related with the main thread
//如果不給任何參數的話會用當前線程對應的Looper(這裏就是Main Looper)爲Handler裏面的成員mLooper賦值
mHandler = new EventHandler(looper);
//mHandler = new EventHandler();
// 清除整個MessageQueue裏的消息
mHandler.removeMessages(0);
String obj = "This main thread's message and received by itself!";
//得到Message對象
Message m = mHandler.obtainMessage(1, 1, 1, obj);
// 將Message對象送入到main thread的MessageQueue裏面
mHandler.sendMessage(m);
break;
case 102:
//other線程發送消息給主線程
postRunnable = false;
noLooerThread = new NoLooperThread();
noLooerThread.start();
break;
case 103:
//other thread獲取它自己發送的消息
tv.setText("please look at the error level log for other thread received message");
ownLooperThread = new OwnLooperThread();
ownLooperThread.start();
break;
case 104:
//other thread通過Post Runnable方式發送消息給主線程
postRunnable = true;
noLooerThread = new NoLooperThread();
noLooerThread.start();
break;
case 105:
//主線程發送消息給other thread
if(null!=mOtherThreadHandler){
tv.setText("please look at the error level log for other thread received message from main thread");
String msgObj = "message from mainThread";
Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
mOtherThreadHandler.sendMessage(mainThreadMsg);
}
break;
case 106:
finish();
break;
}
}
class EventHandler extends Handler
{
public EventHandler(Looper looper) {
super(looper);
}
public EventHandler() {
super();
}
public void handleMessage(Message msg) {
//可以根據msg.what執行不同的處理,這裏沒有這麼做
switch(msg.what){
case 1:
tv.setText((String)msg.obj);
break;
case 2:
tv.setText((String)msg.obj);
noLooerThread.stop();
break;
case 3:
//不能在非主線程的線程裏面更新UI,所以這裏通過Log打印收到的消息
Log.e(sTag, (String)msg.obj);
ownLooperThread.stop();
break;
default:
//不能在非主線程的線程裏面更新UI,所以這裏通過Log打印收到的消息
Log.e(sTag, (String)msg.obj);
break;
}
}
}
//NoLooperThread
class NoLooperThread extends Thread{
private EventHandler mNoLooperThreadHandler;
public void run() {
Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //這是一個static函數
String obj;
if(myLooper == null){
mNoLooperThreadHandler = new EventHandler(mainLooper);
obj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
}
else {
mNoLooperThreadHandler = new EventHandler(myLooper);
obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
}
mNoLooperThreadHandler.removeMessages(0);
if(false == postRunnable){
//send message to main thread
Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj);
mNoLooperThreadHandler.sendMessage(m);
Log.e(sTag, "NoLooperThread id:" + this.getId());
}else{
//下面new出來的實現了Runnable接口的對象中run函數是在Main Thread中執行,不是在NoLooperThread中執行
//注意Runnable是一個接口,它裏面的run函數被執行時不會再新建一個線程
//您可以在run上加斷點然後在eclipse調試中看它在哪個線程中執行
mNoLooperThreadHandler.post(new Runnable(){
@Override
public void run() {
tv.setText("update UI through handler post runnalbe mechanism!");
noLooerThread.stop();
}
});
}
}
}

//OwnLooperThread has his own message queue by execute Looper.prepare();
class OwnLooperThread extends Thread{
private EventHandler mOwnLooperThreadHandler;
public void run() {
Looper.prepare();
Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //這是一個static函數
String obj;
if(myLooper == null){
mOwnLooperThreadHandler = new EventHandler(mainLooper);
obj = "OwnLooperThread has no looper and handleMessage function executed in main thread!";
}
else {
mOwnLooperThreadHandler = new EventHandler(myLooper);
obj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!";
}
mOwnLooperThreadHandler.removeMessages(0);
//給自己發送消息
Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj);
mOwnLooperThreadHandler.sendMessage(m);
Looper.loop();
}
}

//ReceiveMessageThread has his own message queue by execute Looper.prepare();
class ReceiveMessageThread extends Thread{
public void run() {
Looper.prepare();
mOtherThreadHandler = new Handler(){
public void handleMessage(Message msg) {
Log.e(sTag, (String)msg.obj);
}
};
Looper.loop();
}
}

}



使用Looper.myLooper靜態方法可以取得當前線程的Looper對象。

使用mHandler = new EevntHandler(Looper.myLooper()); 可建立用來處理當前線程的Handler對象;其中,EevntHandler是Handler的子類。

使用mHandler = new EevntHandler(Looper.getMainLooper()); 可建立用來處理main線程的Handler對象;其中,EevntHandler是Handler的子類。


[b]主線程發送消息:[/b]

在onClick的case 101中創建一個繼承自Handler的EventHandler對象,然後獲取一個消息,然後通過EventHandler對象調用 sendMessage把消息發送到主線程的MessageQueue中。主線程由系統創建,系統會給它建立一個Looper對象和 MessageQueue,所以可以接收消息。這裏只要根據主線程的Looper對象初始化EventHandler對象,就可以通過 EventHandler對象發送消息到主線程的消息隊列中。

[b]主線程處理消息:[/b]

這裏是通過 EventHandler的handleMessage函數處理的,其中收到的Message對象中what值爲一的消息就是發送給它的,然後把消息裏面附帶的字符串在TextView上顯示出來。

[b]其他線程發送消息(這裏是說不使用Runnable作爲callback的消息):[/b]

首先 postRunnable設爲false,表示不通過Runnable方式進行消息相關的操作。然後啓動線程noLooerThread, 然後以主線程的Looper對象爲參數建立EventHandler的對象mNoLooperThreadHandler,然後獲取一個Message並把一個字符串賦值給它的一個成員obj,然後通過mNoLooperThreadHandler把消息發送到主線程的MessageQueue中。

[b]主線程處理消息:[/b]

這裏是通過 EventHandler的handleMessage函數處理的,其中收到的Message對象中what值爲二的消息就是上面發送給它的,然後把消息裏面附帶的字符串在TextView上顯示出來。


[b]其他線程發送消息:[/b]

其他非主線程建立後沒有自己的Looper對象,所以也沒有MessageQueue,需要給非主線程發送消息時需要建立MessageQueue以便接收消息。下面說明如何給自己建立MessageQueue和Looper對象。從OwnLooperThread的run函數中可以看見有一個 Looper.prepare()調用,這個就是用來建立非主線程的MessageQueue和Looper對象的。

所以這裏的發送消息過程是建立線程mOwnLooperThread,然後線程建立自己的Looper和MessageQueue對象,然後根據上面建立的Looper對象建立對應的EventHandler對象mOwnLooperThreadHandler,然後由mOwnLooperThreadHandler建立消息並且發送到自己的MessageQueue裏面。

[b]其他線程處理接收的消息:[/b]

線程要接收消息需要在run函數中調用Looper.loop(),然後loop函數會從MessageQueue中取出消息交給對應的Handler對象 mOwnLooperThreadHandler處理,在mOwnLooperThreadHandler的handleMessage函數中會把 Message對象中what值爲三的消息(上面發送的消息)在Log中打印出來,可以通過Logcat工具查看log。

[b]其他線程發送消息(這裏是說使用Runnable作爲callback的消息):[/b]

首先 postRunnable設爲true,表示通過Runnable方式進行消息相關的操作。然後啓動線程noLooerThread, 然後以主線程的Looper對象爲參數建立EventHandler的對象mNoLooperThreadHandler,然後獲取一個Message並把一個字符串賦值給它的一個成員obj,然後通過mNoLooperThreadHandler把消息發送到主線程的MessageQueue中。
[b]
主線程處理消息:[/b]

主線程收到上面發送的Message後直接運行上面Runnable對象中的run函數進行相應的操作。run函數通過Log打印一個字符串,可以通過Logcat工具查看 log。

[b]主線程發送消息:[/b]

這裏首先要求線程receiveMessageThread運行(在onCreate函數中完成),並且準備好自己的 Looper和MessageQueue(這個通過ReceiveMessageThread中的run函數中的Looper.prepare()調用完成),然後根據建立的Looper對象初始化Handler對象mOtherThreadHandler。然後在onClick的case 105中由mOtherThreadHandler建立一個消息(消息中有一個字符串對象)並且發送到線程receiveMessageThread中的 MessageQueue中。

[b]其他線程處理接收的消息:[/b]

線程要接收消息需要在run函數中調用Looper.loop(),然後loop函數會從MessageQueue中取出消息交給對應的Handler對象mOtherThreadHandler處理,在mOtherThreadHandler的handleMessage函數中會把Message對象中的字符串對象在Log中打印出來,可以通過Logcat工具查看log。
發佈了43 篇原創文章 · 獲贊 0 · 訪問量 2672
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章