1.活用Android線程間通信的Message機(jī)制 1.1.Message 代碼在frameworks\base\core\java\android\Os\Message.java中。
Message.obtain函數(shù):有多個(gè)obtain函數(shù),主要功能一樣,只是參數(shù)不一樣。作用是從Message Pool中取出一個(gè)Message,如果Message Pool中已經(jīng)沒(méi)有Message可取則新建一個(gè)Message返回,同時(shí)用對(duì)應(yīng)的參數(shù)給得到的Message對(duì)象賦值。
Message Pool:大小為10個(gè);通過(guò)Message.mPool->(Message并且Message.next)-> (Message并且Message.next)-> (Message并且Message.next)...構(gòu)造一個(gè)Message Pool。Message Pool的第一個(gè)元素直接new出來(lái),然后把Message.mPool(static類的static變量)指向它。其他的元素都是使用完的 Message通過(guò)Message的recycle函數(shù)清理后放到Message Pool(通過(guò)Message Pool最后一個(gè)Message的next指向需要回收的Message的方式實(shí)現(xiàn))。下圖為Message Pool的結(jié)構(gòu):
1.2.MessageQueue MessageQueue里面有一個(gè)收到的Message的對(duì)列:
MessageQueue.mMessages(static變量)->( Message并且Message.next)-> ( Message并且Message.next)->...,下圖為接收消息的消息隊(duì)列:
上層代碼通過(guò)Handler的sendMessage等函數(shù)放入一個(gè)message到MessageQueue里面時(shí)最終會(huì)調(diào)用MessageQueue的 enqueueMessage函數(shù)。enqueueMessage根據(jù)上面的接收的Message的隊(duì)列的構(gòu)造把接收到的Message放入隊(duì)列中。
MessageQueue的removeMessages函數(shù)根據(jù)上面的接收的Message的隊(duì)列的構(gòu)造把接收到的Message從隊(duì)列中刪除,并且調(diào)用對(duì)應(yīng)Message對(duì)象的recycle函數(shù)把不用的Message放入Message Pool中。
1.3.Looper Looper對(duì)象的創(chuàng)建是通過(guò)prepare函數(shù),而且每一個(gè)Looper對(duì)象會(huì)和一個(gè)線程關(guān)聯(lián)
- public static final void prepare() {
- if (sThreadLocal.get() != null) {
- throw new RuntimeException("Only one Looper may be created per thread");
- }
- sThreadLocal.set(new Looper());
- }
public static final void prepare() {if (sThreadLocal.get() != null) {throw new RuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(new Looper());}
Looper對(duì)象創(chuàng)建時(shí)會(huì)創(chuàng)建一個(gè)MessageQueue,主線程默認(rèn)會(huì)創(chuàng)建一個(gè)Looper從而有MessageQueue,其他線程默認(rèn)是沒(méi)有 MessageQueue的不能接收Message,如果需要接收Message則需要通過(guò)prepare函數(shù)創(chuàng)建一個(gè)MessageQueue。具體操作請(qǐng)見(jiàn)示例代碼。
- private Looper() {
- mQueue = new MessageQueue();
- mRun = true;
- mThread = Thread.currentThread();
- }
private Looper() {mQueue = new MessageQueue();mRun = true;mThread = Thread.currentThread();}
prepareMainLooper函數(shù)只給主線程調(diào)用(系統(tǒng)處理,程序員不用處理),它會(huì)調(diào)用prepare建立Looper對(duì)象和MessageQueue。
- public static final void prepareMainLooper() {
- prepare();
- setMainLooper(myLooper());
- if (Process.supportsProcesses()) {
- myLooper().mQueue.mQuitAllowed = false;
- }
- }
public static final void prepareMainLooper() {prepare();setMainLooper(myLooper());if (Process.supportsProcesses()) {myLooper().mQueue.mQuitAllowed = false;}}
Loop函數(shù)從MessageQueue中從前往后取出Message,然后通過(guò)Handler的dispatchMessage函數(shù)進(jìn)行消息的處理(可見(jiàn)消息的處理是Handler負(fù)責(zé)的),消息處理完了以后通過(guò)Message對(duì)象的recycle函數(shù)放到Message Pool中,以便下次使用,通過(guò)Pool的處理提供了一定的內(nèi)存管理從而加速消息對(duì)象的獲取。至于需要定時(shí)處理的消息如何做到定時(shí)處理,請(qǐng)見(jiàn) MessageQueue的next函數(shù),它在取Message來(lái)進(jìn)行處理時(shí)通過(guò)判斷MessageQueue里面的Message是否符合時(shí)間要求來(lái)決定是否需要把Message取出來(lái)做處理,通過(guò)這種方式做到消息的定時(shí)處理。
- public static final void loop() {
- Looper me = myLooper();
- MessageQueue queue = me.mQueue;
- while (true) {
- Message msg = queue.next();
-
-
-
- if (msg != null) {
- if (msg.target == null) {
-
- return;
- }
-
- if (me.mLogging!= null)
- me.mLogging.println(">>>>> Dispatching to " + msg.target + " "+ msg.callback + ": " + msg.what);
- msg.target.dispatchMessage(msg);
- if (me.mLogging!= null)
- me.mLogging.println("<<<<< Finished to" + msg.target + " "+ msg.callback);
- msg.recycle();
- }
- }
- }
public static final void loop() {Looper me = myLooper();MessageQueue queue = me.mQueue;while (true) {Message msg = queue.next(); // might block//if (!me.mRun) {// break;//}if (msg != null) {if (msg.target == null) {// No target is a magic identifier for the quit messagereturn;}if (me.mLogging!= null)me.mLogging.println(">>>>> Dispatching to " + msg.target + " "+ msg.callback + ": " + msg.what);msg.target.dispatchMessage(msg);if (me.mLogging!= null)me.mLogging.println("<<<<< Finished to" + msg.target + " "+ msg.callback);msg.recycle();}}}
1.4.Handler Handler的構(gòu)造函數(shù)表示Handler會(huì)有成員變量指向Looper和MessageQueue,后面我們會(huì)看到?jīng)]什么需要這些引用;至于callback是實(shí)現(xiàn)了Callback接口的對(duì)象,后面會(huì)看到這個(gè)對(duì)象的作用。
- public Handler(Looper looper, Callback callback) {
- mLooper = looper;
- mQueue = looper.mQueue;
- mCallback = callback;
- }
-
- public interface Callback {
- public boolean handleMessage(Message msg);
- }
public Handler(Looper looper, Callback callback) {mLooper = looper;mQueue = looper.mQueue;mCallback = callback;}public interface Callback {public boolean handleMessage(Message msg);}
獲取消息:直接通過(guò)Message的obtain方法獲取一個(gè)Message對(duì)象。
- public final Message obtainMessage(int what, int arg1, int arg2, Object obj){
- return Message.obtain(this, what, arg1, arg2, obj);
- }
public final Message obtainMessage(int what, int arg1, int arg2, Object obj){return Message.obtain(this, what, arg1, arg2, obj);}
發(fā)送消息:通過(guò)MessageQueue的enqueueMessage把Message對(duì)象放到MessageQueue的接收消息隊(duì)列中
- public boolean sendMessageAtTime(Message msg, long uptimeMillis){
- boolean sent = false;
- MessageQueue queue = mQueue;
- if (queue != null) {
- msg.target = this;
- sent = queue.enqueueMessage(msg, uptimeMillis);
- } else {
- RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");
- Log.w("Looper", e.getMessage(), e);
- }
- return sent;
- }
public boolean sendMessageAtTime(Message msg, long uptimeMillis){boolean sent = false;MessageQueue queue = mQueue;if (queue != null) {msg.target = this;sent = queue.enqueueMessage(msg, uptimeMillis);} else {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);}return sent;}
線程如何處理MessageQueue中接收的消息:在Looper的loop函數(shù)中循環(huán)取出MessageQueue的接收消息隊(duì)列中的消息,然后調(diào)用 Hander的dispatchMessage函數(shù)對(duì)消息進(jìn)行處理,至于如何處理(相應(yīng)消息)則由用戶指定(三個(gè)方法,優(yōu)先級(jí)從高到低:Message里面的Callback,一個(gè)實(shí)現(xiàn)了Runnable接口的對(duì)象,其中run函數(shù)做處理工作;Handler里面的mCallback指向的一個(gè)實(shí)現(xiàn)了 Callback接口的對(duì)象,里面的handleMessage進(jìn)行處理;處理消息Handler對(duì)象對(duì)應(yīng)的類繼承并實(shí)現(xiàn)了其中 handleMessage函數(shù),通過(guò)這個(gè)實(shí)現(xiàn)的handleMessage函數(shù)處理消息)。
- public void dispatchMessage(Message msg) {
- if (msg.callback != null) {
- handleCallback(msg);
- } else {
- if (mCallback != null) {
- if (mCallback.handleMessage(msg)) {
- return;
- }
- }
- handleMessage(msg);
- }
- }
public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}}
Runnable說(shuō)明:Runnable只是一個(gè)接口,實(shí)現(xiàn)了這個(gè)接口的類對(duì)應(yīng)的對(duì)象也只是個(gè)普通的對(duì)象,并不是一個(gè)Java中的Thread。Thread類經(jīng)常使用Runnable,很多人有誤解,所以這里澄清一下。
從上可知以下關(guān)系圖:
其中清理Message是Looper里面的loop函數(shù)指把處理過(guò)的Message放到Message的Pool里面去,如果里面已經(jīng)超過(guò)最大值10個(gè),則丟棄這個(gè)Message對(duì)象。
調(diào)用Handler是指Looper里面的loop函數(shù)從MessageQueue的接收消息隊(duì)列里面取出消息,然后根據(jù)消息指向的Handler對(duì)象調(diào)用其對(duì)應(yīng)的處理方法。
1.5.代碼示例 下面我們會(huì)以android實(shí)例來(lái)展示對(duì)應(yīng)的功能,程序界面于下:
程序代碼如下,后面部分有代碼說(shuō)明:
- 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;
-
-
- @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);
-
-
- receiveMessageThread = new ReceiveMessageThread();
- receiveMessageThread.start();
- }
-
-
- @Override
- public void onClick(View v) {
- switch(v.getId()){
- case 101:
-
- Looper looper;
- looper = Looper.myLooper();
-
- mHandler = new EventHandler(looper);
-
-
- mHandler.removeMessages(0);
- String obj = "This main thread's message and received by itself!";
-
- Message m = mHandler.obtainMessage(1, 1, 1, obj);
-
- mHandler.sendMessage(m);
- break;
- case 102:
-
- postRunnable = false;
- noLooerThread = new NoLooperThread();
- noLooerThread.start();
- break;
- case 103:
-
- tv.setText("please look at the error level log for other thread received message");
- ownLooperThread = new OwnLooperThread();
- ownLooperThread.start();
- break;
- case 104:
-
- postRunnable = true;
- noLooerThread = new NoLooperThread();
- noLooerThread.start();
- break;
- case 105:
-
- 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) {
-
- switch(msg.what){
- case 1:
- tv.setText((String)msg.obj);
- break;
- case 2:
- tv.setText((String)msg.obj);
- noLooerThread.stop();
- break;
- case 3:
-
- Log.e(sTag, (String)msg.obj);
- ownLooperThread.stop();
- break;
- default:
-
- Log.e(sTag, (String)msg.obj);
- break;
- }
- }
- }
-
- class NoLooperThread extends Thread{
- private EventHandler mNoLooperThreadHandler;
- public void run() {
- Looper myLooper, mainLooper;
- myLooper = Looper.myLooper();
- mainLooper = Looper.getMainLooper();
- 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){
-
- Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj);
- mNoLooperThreadHandler.sendMessage(m);
- Log.e(sTag, "NoLooperThread id:" + this.getId());
- }else{
-
-
-
- mNoLooperThreadHandler.post(new Runnable(){
- @Override
- public void run() {
- tv.setText("update UI through handler post runnalbe mechanism!");
- noLooerThread.stop();
- }
- });
- }
- }
- }
-
-
- class OwnLooperThread extends Thread{
- private EventHandler mOwnLooperThreadHandler;
- public void run() {
- Looper.prepare();
- Looper myLooper, mainLooper;
- myLooper = Looper.myLooper();
- mainLooper = Looper.getMainLooper();
- 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();
- }
- }
-
-
- 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();
- }
- }
-
- }
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); //主線程要發(fā)送消息給other thread, 這里創(chuàng)建那個(gè)other thread receiveMessageThread = new ReceiveMessageThread(); receiveMessageThread.start(); }//implement the OnClickListener interface@Overridepublic void onClick(View v) { switch(v.getId()){ case 101: //主線程發(fā)送消息給自己 Looper looper; looper = Looper.myLooper(); //get the Main looper related with the main thread //如果不給任何參數(shù)的話會(huì)用當(dāng)前線程對(duì)應(yīng)的Looper(這里就是Main Looper)為Handler里面的成員mLooper賦值 mHandler = new EventHandler(looper); //mHandler = new EventHandler(); // 清除整個(gè)MessageQueue里的消息 mHandler.removeMessages(0); String obj = "This main thread's message and received by itself!"; //得到Message對(duì)象 Message m = mHandler.obtainMessage(1, 1, 1, obj); // 將Message對(duì)象送入到main thread的MessageQueue里面 mHandler.sendMessage(m); break; case 102: //other線程發(fā)送消息給主線程 postRunnable = false; noLooerThread = new NoLooperThread(); noLooerThread.start(); break; case 103: //other thread獲取它自己發(fā)送的消息 tv.setText("please look at the error level log for other thread received message"); ownLooperThread = new OwnLooperThread(); ownLooperThread.start(); break; case 104: //other thread通過(guò)Post Runnable方式發(fā)送消息給主線程 postRunnable = true; noLooerThread = new NoLooperThread(); noLooerThread.start(); break; case 105: //主線程發(fā)送消息給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) { //可以根據(jù)msg.what執(zhí)行不同的處理,這里沒(méi)有這么做 switch(msg.what){ case 1: tv.setText((String)msg.obj); break; case 2: tv.setText((String)msg.obj); noLooerThread.stop(); break; case 3: //不能在非主線程的線程里面更新UI,所以這里通過(guò)Log打印收到的消息 Log.e(sTag, (String)msg.obj); ownLooperThread.stop(); break; default: //不能在非主線程的線程里面更新UI,所以這里通過(guò)Log打印收到的消息 Log.e(sTag, (String)msg.obj); break; } }}//NoLooperThreadclass NoLooperThread extends Thread{ private EventHandler mNoLooperThreadHandler; public void run() { Looper myLooper, mainLooper; myLooper = Looper.myLooper(); mainLooper = Looper.getMainLooper(); //這是一個(gè)static函數(shù) 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出來(lái)的實(shí)現(xiàn)了Runnable接口的對(duì)象中run函數(shù)是在Main Thread中執(zhí)行,不是在NoLooperThread中執(zhí)行 //注意Runnable是一個(gè)接口,它里面的run函數(shù)被執(zhí)行時(shí)不會(huì)再新建一個(gè)線程 //您可以在run上加斷點(diǎn)然后在eclipse調(diào)試中看它在哪個(gè)線程中執(zhí)行 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(); //這是一個(gè)static函數(shù) 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); //給自己發(fā)送消息 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(); }}}
說(shuō)明(代碼詳細(xì)解釋請(qǐng)見(jiàn)后文):
使用Looper.myLooper靜態(tài)方法可以取得當(dāng)前線程的Looper對(duì)象。
使用mHandler = new EevntHandler(Looper.myLooper()); 可建立用來(lái)處理當(dāng)前線程的Handler對(duì)象;其中,EevntHandler是Handler的子類。
使用mHandler = new EevntHandler(Looper.getMainLooper()); 可建立用來(lái)處理main線程的Handler對(duì)象;其中,EevntHandler是Handler的子類。
1.5.1.主線程給自己發(fā)送消息示例 主線程發(fā)送消息:
在onClick的case 101中創(chuàng)建一個(gè)繼承自Handler的EventHandler對(duì)象,然后獲取一個(gè)消息,然后通過(guò)EventHandler對(duì)象調(diào)用 sendMessage把消息發(fā)送到主線程的MessageQueue中。主線程由系統(tǒng)創(chuàng)建,系統(tǒng)會(huì)給它建立一個(gè)Looper對(duì)象和 MessageQueue,所以可以接收消息。這里只要根據(jù)主線程的Looper對(duì)象初始化EventHandler對(duì)象,就可以通過(guò) EventHandler對(duì)象發(fā)送消息到主線程的消息隊(duì)列中。
主線程處理消息:
這里是通過(guò)EventHandler的handleMessage函數(shù)處理的,其中收到的Message對(duì)象中what值為一的消息就是發(fā)送給它的,然后把消息里面附帶的字符串在TextView上顯示出來(lái)。
1.5.2.其他線程給主線程發(fā)送消息示例 其他線程發(fā)送消息(這里是說(shuō)不使用Runnable作為callback的消息):
首先 postRunnable設(shè)為false,表示不通過(guò)Runnable方式進(jìn)行消息相關(guān)的操作。然后啟動(dòng)線程noLooerThread,然后以主線程的Looper對(duì)象為參數(shù)建立EventHandler的對(duì)象mNoLooperThreadHandler,然后獲取一個(gè)Message并把一個(gè)字符串賦值給它的一個(gè)成員obj,然后通過(guò)mNoLooperThreadHandler把消息發(fā)送到主線程的MessageQueue中。
主線程處理消息:
這里是通過(guò)EventHandler的handleMessage函數(shù)處理的,其中收到的Message對(duì)象中what值為二的消息就是上面發(fā)送給它的,然后把消息里面附帶的字符串在TextView上顯示出來(lái)。
1.5.3.其他線程給自己發(fā)送消息示例 其他線程發(fā)送消息:
其他非主線程建立后沒(méi)有自己的Looper對(duì)象,所以也沒(méi)有MessageQueue,需要給非主線程發(fā)送消息時(shí)需要建立MessageQueue以便接收消息。下面說(shuō)明如何給自己建立MessageQueue和Looper對(duì)象。從OwnLooperThread的run函數(shù)中可以看見(jiàn)有一個(gè) Looper.prepare()調(diào)用,這個(gè)就是用來(lái)建立非主線程的MessageQueue和Looper對(duì)象的。
所以這里的發(fā)送消息過(guò)程是建立線程mOwnLooperThread,然后線程建立自己的Looper和MessageQueue對(duì)象,然后根據(jù)上面建立的Looper對(duì)象建立對(duì)應(yīng)的EventHandler對(duì)象mOwnLooperThreadHandler,然后由mOwnLooperThreadHandler建立消息并且發(fā)送到自己的MessageQueue里面。
其他線程處理接收的消息:
線程要接收消息需要在run函數(shù)中調(diào)用Looper.loop(),然后loop函數(shù)會(huì)從MessageQueue中取出消息交給對(duì)應(yīng)的Handler對(duì)象 mOwnLooperThreadHandler處理,在mOwnLooperThreadHandler的handleMessage函數(shù)中會(huì)把 Message對(duì)象中what值為三的消息(上面發(fā)送的消息)在Log中打印出來(lái),可以通過(guò)Logcat工具查看log。
1.5.4.其他線程以Runnable為消息參數(shù)給主線程發(fā)送消息示例 其他線程發(fā)送消息(這里是說(shuō)使用Runnable作為callback的消息):
首先 postRunnable設(shè)為true,表示通過(guò)Runnable方式進(jìn)行消息相關(guān)的操作。然后啟動(dòng)線程noLooerThread,然后以主線程的Looper對(duì)象為參數(shù)建立EventHandler的對(duì)象mNoLooperThreadHandler,然后獲取一個(gè)Message并把一個(gè)字符串賦值給它的一個(gè)成員obj,然后通過(guò)mNoLooperThreadHandler把消息發(fā)送到主線程的MessageQueue中。
主線程處理消息:
主線程收到上面發(fā)送的Message后直接運(yùn)行上面Runnable對(duì)象中的run函數(shù)進(jìn)行相應(yīng)的操作。run函數(shù)通過(guò)Log打印一個(gè)字符串,可以通過(guò)Logcat工具查看log。
1.5.5.主線程給其他線程發(fā)送消息示例 主線程發(fā)送消息:
這里首先要求線程receiveMessageThread運(yùn)行(在onCreate函數(shù)中完成),并且準(zhǔn)備好自己的Looper和 MessageQueue(這個(gè)通過(guò)ReceiveMessageThread中的run函數(shù)中的Looper.prepare()調(diào)用完成),然后根據(jù)建立的Looper對(duì)象初始化Handler對(duì)象mOtherThreadHandler。然后在onClick的case 105中由mOtherThreadHandler建立一個(gè)消息(消息中有一個(gè)字符串對(duì)象)并且發(fā)送到線程receiveMessageThread中的 MessageQueue中。
其他線程處理接收的消息:
線程要接收消息需要在run函數(shù)中調(diào)用Looper.loop(),然后loop函數(shù)會(huì)從MessageQueue中取出消息交給對(duì)應(yīng)的Handler對(duì)象mOtherThreadHandler處理,在mOtherThreadHandler的handleMessage函數(shù)中會(huì)把Message對(duì)象中的字符串對(duì)象在Log中打印出來(lái),可以通過(guò)Logcat工具查看log。