Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 系列:Message 機制的靈活應用

編輯:Android 開發實例

以下用一個完整實例來展示 Android 訊息機制的各種用法。程式以純程式碼建立版面,放了六顆按鈕,每顆對應一種不同的訊息傳遞情境。

版面與按鈕配置

15  public class MessageExample extends Activity implements OnClickListener {
16      private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
17      private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
18      public TextView tv;
19      private EventHandler mHandler;
20      private Handler mOtherThreadHandler = null;
21      private Button btn, btn2, btn3, btn4, btn5, btn6;
22      private NoLooperThread noLooerThread = null;
23      private OwnLooperThread ownLooperThread = null;
24      private ReceiveMessageThread receiveMessageThread = null;
25      private boolean postRunnable = false;
26
27      @Override
28      public void onCreate(Bundle savedInstanceState) {
29          super.onCreate(savedInstanceState);
30          LinearLayout layout = new LinearLayout(this);
31          layout.setOrientation(LinearLayout.VERTICAL);
32          // btn(101) ~ btn6(106) 依序加入版面,文字說明各自的情境
...
77          // 主執行緒要送訊息給 other thread,先把它建起來
78          receiveMessageThread = new ReceiveMessageThread();
79          receiveMessageThread.start();
80      }

六種訊息情境

情境一:主執行緒傳訊息給自己

87  case 101:
88      Looper looper = Looper.myLooper();   // 取得與主執行緒相關的 Looper
89      mHandler = new EventHandler(looper);
90      mHandler.removeMessages(0);          // 先清空整個 MessageQueue
91      String obj = "This main thread's message and received by itself!";
92      Message m = mHandler.obtainMessage(1, 1, 1, obj);
93      mHandler.sendMessage(m);             // 送進主執行緒的 MessageQueue
94      break;

主執行緒由系統建立,天生就有 Looper 與 MessageQueue,所以只要用它的 Looper 初始化 Handler 就能收訊息。若不給 Handler 傳任何參數,它會自動使用「建立它的執行緒」對應的 Looper。

情境二:其他執行緒傳訊息給主執行緒(非 Runnable 方式)

104     postRunnable = false;
105     noLooerThread = new NoLooperThread();
106     noLooerThread.start();

NoLooperThread 的 run 方法中,關鍵是判斷自己到底有沒有 Looper,再決定 Handler 要綁到哪裡:

168     myLooper   = Looper.myLooper();
169     mainLooper = Looper.getMainLooper();   // 靜態方法
170     if (myLooper == null) {
171         mNoLooperThreadHandler = new EventHandler(mainLooper);
172         obj = "NoLooperThread has no looper; handleMessage runs in main thread!";
173     } else {
174         mNoLooperThreadHandler = new EventHandler(myLooper);
175         obj = "handleMessage runs in NoLooperThread itself!";
176     }

因為這個執行緒沒呼叫 Looper.prepare(),myLooper 為 null,Handler 於是綁到主 Looper 上,handleMessage() 也在主執行緒執行,可以直接更新 UI。

情境三:執行緒傳訊息給自己

OwnLooperThread 在 run 一開頭就呼叫 Looper.prepare(),為自己建立 MessageQueue 與 Looper:

204     Looper.prepare();
205     myLooper = Looper.myLooper();   // 這次不為 null
206     mOwnLooperThreadHandler = new EventHandler(myLooper);
...
219     // 給自己送訊息
220     Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj);
221     mOwnLooperThreadHandler.sendMessage(m);
222     Looper.loop();                  // 啟動循環,開始收訊息

要接收訊息就一定要呼叫 Looper.loop(),它會從 MessageQueue 取訊息交給對應 Handler 處理。因為此時身處子執行緒,handleMessage() 中不能更新 UI,範例改用 Log 輸出結果。

情境四:以 Runnable 作為回呼

114     postRunnable = true;
115     noLooerThread = new NoLooperThread();
116     noLooerThread.start();

NoLooperThread 收到旗標後改走另一條路:

190         mNoLooperThreadHandler.post(new Runnable(){
191             @Override
192             public void run() {
193                 tv.setText("update UI through handler post runnable mechanism!");
194             }
195         });

這裡有個很多人會誤解的地方:Runnable 只是一個介面,它的 run() 不會自己開新執行緒。這個 Runnable 雖然由子執行緒 post 出去,實際執行位置卻是 Handler 所綁定的那個執行緒——也就是主執行緒,因此裡面更新 UI 是安全的。你可以在 run 上打斷點,用除錯器確認它跑在哪條執行緒。

情境五:主執行緒傳訊息給其他執行緒

前提是先有一條帶 Looper 的執行緒在等:

226 class ReceiveMessageThread extends Thread {
227     public void run() {
228         Looper.prepare();
229         mOtherThreadHandler = new Handler() {
230             public void handleMessage(Message msg) {
231                 Log.e(sTag, (String) msg.obj);
232             }
233         };
234         Looper.loop();
235     }
236 }

於是主執行緒就能持有 mOtherThreadHandler 並投遞訊息:

121 case 105:
122     if (null != mOtherThreadHandler) {
123         String msgObj = "message from mainThread";
124         Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
125         mOtherThreadHandler.sendMessage(mainThreadMsg);
126     }
127     break;

情境六:離開

按 106 直接 finish() 結束 Activity。

Handler 端的統一處理

142     public void handleMessage(Message msg) {
143         switch (msg.what) {
144         case 1: tv.setText((String) msg.obj); break;
145         case 2: tv.setText((String) msg.obj); noLooerThread.stop(); break;
146         case 3: // 非主執行緒不能更新 UI,改用 Log
147                 Log.e(sTag, (String) msg.obj); ownLooperThread.stop(); break;
148         default: Log.e(sTag, (String) msg.obj); break;
149         }
150     }

用 msg.what 分流是標準做法;msg.obj 則用來攜帶任意物件。

幾個該記住的規則

  • Looper.myLooper() 取得當前執行緒的 Looper;Looper.getMainLooper() 取得主執行緒的。
  • Handler 建立時會綁定到建立它的執行緒的 Looper;要跨執行緒溝通,就得把對方的 Looper 明確傳進建構子。
  • 非主執行緒預設沒有 Looper 與 MessageQueue,Looper.prepare() 就是拿來建立它們的。
  • 光 prepare 不夠,還要 Looper.loop() 才會開始消費訊息。
  • 只有主執行緒能更新 UI。子執行緒收到訊息想改畫面,得把訊息轉發給主執行緒的 Handler,或用 post(Runnable) 借用主執行緒執行。
  • Handler.post(Runnable) 不會建立新執行緒,它只是在目標 Looper 的佇列裡排一件工作。

轉自:https://www.cnblogs.com/jk1001/archive/2010/07/28/1786577.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved