Android之理解Looper、Handler、Message、MessageQueue

來源:互聯網
上載者:User

一、概述 

        關於android線程間的通訊其實是很重要的一個問題,所以必有要對此有一個清晰的認識。題目並不完整,還應該加上Thread以及Runnable,下面開始分別介紹。

二、介紹

        1、Message

                Message定義一個訊息包含一個描述和任意的資料對象,可以發送給一個Handler。這個對象包含兩個額外的int欄位和一個額外的對象欄位。這個類有幾個比較重要的欄位:
        a.arg1和arg2:我們可以使用兩個欄位用來存放我們需要傳遞的整型值。
        b.obj:該欄位是Object類型,我們可以讓該欄位傳遞某個多項到訊息的接受者中。
        c.what:這個欄位可以說是訊息的標誌,在訊息處理中,我們可以根據這個欄位的不同的值進行不同的處理,類似於我們在處理Button事件時,通過switch(v.getId())判斷是點擊了哪個按鈕。

     在使用Message時,我們可以通過new Message()建立一個Message執行個體,但是Android 更推薦我們通過Message.obtain()或者Handler.obtainMessage()擷取Message對象。這並不一定是直接建立一個新的執行個體,而是先從訊息池中看有沒有可用的Message執行個體,存在則直接取出並返回這個執行個體。反之如果訊息池中沒有可用的Message執行個體,則根據給定的參數new一個新Message對象。通過分析源碼可得知,Android系統預設情況下在訊息池中執行個體化10個Message對象。

     2、MessageQueue

        訊息佇列,用來存放Message對象的資料結構,按照“先進先出”的原則存放訊息。存放並非實際意義的儲存,而是將Message對象以鏈表的方式串聯起來的。MessageQueue對象不需要我們自己建立,而是有Looper對象對其進行管理,一個線程最多隻可以擁有一個 MessageQueue。我們可以通過Looper.myQueue()擷取當前線程中的MessageQueue。

     3、Looper

        Looper是用於給一個線程添加一個訊息佇列(MessageQueue),並且迴圈等待,當有訊息時會喚起線程來處理訊息的一個工具,直到線程結束為止。通常情況下不會用到Looper,因為對於Activity,Service等系統組件,Frameworks已經為我們初始化好了線程(俗稱的UI線程或主線程),在其內含有一個Looper,和由Looper建立的訊息佇列,所以主線程會一直運行,處理使用者事件,直到某些事件(BACK)退出。MessageQueue的管理者,在一個線程中,如果存在Looper對象,則必定存在MessageQueue對象,並且只存在一個Looper對象和一個MessageQueue對象。在Android 系統中,除了主線程有預設的Looper對象,其它線程預設是沒有Looper對象。如果想讓我們新建立的線程擁有Looper對象時,我們首先應調用Looper.prepare()方法,然後再調用Looper.loop()方法。

        如果,我們需要建立一個線程,並且這個線程要能夠迴圈處理其他線程發來的訊息事件,或者需要長期與其他線程進行複雜的互動,這時就需要用到Looper來給線程建立訊息佇列。

        使用Looper也非常的簡單,它的方法比較少,最主要的有四個:
          public static prepare();
          public static myLooper();
          public static loop();
          public void quit();
       使用方法如下:
          1. 在每個線程的run()方法中的最開始調用Looper.prepare(),這是為線程初始化訊息佇列。
          2. 之後調用Looper.myLooper()擷取此Looper對象的引用。這不是必須的,但是如果你需要儲存Looper對象的話,一定要在prepare()之後,否則調用在此對象上的方法不一定有效果,如looper.quit()就不會退出。
          3. 在run()方法中添加Handler來處理訊息
          4. 添加Looper.loop()調用,這是讓線程的訊息佇列開始運行,可以接收訊息了。
          5. 在想要退出訊息迴圈時,調用Looper.quit()注意,這個方法是要在對象上面調用,很明顯,用對象的意思就是要退出具體哪個Looper。如果run()中無其他動作,線程也將終止運行。

        在API是這樣介紹使用的,大多數與一個訊息迴圈互動 是通過handler來實現的。官方給出一個很典型的例子,如下:

 

  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();      }  }

         下面來看一個執行個體:

 

 

public class LooperDemoActivity extends Activity {    private WorkerThread mWorkerThread;    private TextView mStatusLine;    private Handler mMainHandler;       @Override    public void onCreate(Bundle icicle) {       super.onCreate(icicle);       setContentView(R.layout.looper_demo_activity);       mMainHandler = new Handler() {     @Override     public void handleMessage(Message msg) {       String text = (String) msg.obj;         if (TextUtils.isEmpty(text)) {          return;  }        mStatusLine.setText(text);     } }; mWorkerThread = new WorkerThread(); final Button action = (Button) findViewById(R.id.looper_demo_action); action.setOnClickListener(new View.OnClickListener() {     public void onClick(View v) {  mWorkerThread.executeTask("please do me a favor");     } }); final Button end = (Button) findViewById(R.id.looper_demo_quit); end.setOnClickListener(new View.OnClickListener() {     public void onClick(View v) {  mWorkerThread.exit();     } }); mStatusLine = (TextView) findViewById(R.id.looper_demo_displayer); mStatusLine.setText("Press 'do me a favor' to execute a task, press 'end of service' to stop looper thread");    }       @Override    public void onDestroy() { super.onDestroy(); mWorkerThread.exit(); mWorkerThread = null;    }       private class WorkerThread extends Thread {      protected static final String TAG = "WorkerThread";      private Handler mHandler;      private Looper mLooper; public WorkerThread() {     start(); } public void run() {     // Attention: if you obtain looper before Looper#prepare(), you can still use the looper     // to process message even after you call Looper#quit(), which means the looper does not     //really quit.     Looper.prepare();     // So we should call Looper#myLooper() after Looper#prepare(). Anyway, we should put all stuff between Looper#prepare()     // and Looper#loop().     // In this case, you will receive "Handler{4051e4a0} sending message to a Handler on a dead thread     // 05-09 08:37:52.118: W/MessageQueue(436): java.lang.RuntimeException: Handler{4051e4a0} sending message     // to a Handler on a dead thread", when try to send a message to a looper which Looper#quit() had called,     // because the thread attaching the Looper and Handler dies once Looper#quit() gets called.     mLooper = Looper.myLooper();     // either new Handler() and new Handler(mLooper) will work     mHandler = new Handler(mLooper) {  @Override  public void handleMessage(Message msg) {      /*       * Attention: object Message is not reusable, you must obtain a new one for each time you want to use it.       * Otherwise you got "android.util.AndroidRuntimeException: { what=1000 when=-15ms obj=it is my please       * to serve you, please be patient to wait!........ } This message is already in use."       *///      Message newMsg = Message.obtain();      StringBuilder sb = new StringBuilder();      sb.append("it is my please to serve you, please be patient to wait!\n");      Log.e(TAG, "workerthread, it is my please to serve you, please be patient to wait!");      for (int i = 1; i < 100; i++) {   sb.append(".");   Message newMsg = Message.obtain();   newMsg.obj = sb.toString();   mMainHandler.sendMessage(newMsg);   Log.e(TAG, "workthread, working" + sb.toString());   SystemClock.sleep(100);      }      Log.e(TAG, "workerthread, your work is done.");      sb.append("\nyour work is done");      Message newMsg = Message.obtain();      newMsg.obj = sb.toString();      mMainHandler.sendMessage(newMsg);  }     };     Looper.loop(); } public void exit() {     if (mLooper != null) {  mLooper.quit();  mLooper = null;     } } // This method returns immediately, it just push an Message into Thread's MessageQueue. // You can also call this method continuously, the task will be executed one by one in the // order of which they are pushed into MessageQueue(they are called). public void executeTask(String text) {     if (mLooper == null || mHandler == null) {  Message msg = Message.obtain();  msg.obj = "Sorry man, it is out of service";  mMainHandler.sendMessage(msg);  return;     }     Message msg = Message.obtain();     msg.obj = text;     mHandler.sendMessage(msg); }    }}

          這個執行個體中,主線程中執行任務僅是給服務線程發一個訊息同時把相關資料傳過去,資料會打包成訊息對象(Message),然後放到服務線程的訊息佇列中,主線程的調用返回,此過程很快,所以不會阻塞主線程。服務線程每當有訊息進入訊息佇列後就會被喚醒從隊列中取出訊息,然後執行任務。服務線程可以接收任意數量的任務,也即主線程可以不停的發送訊息給服務線程,這些訊息都會被放進訊息佇列中,服務線程會一個接著一個的執行它們----直到所有的任務都完成(訊息佇列為空白,已無其他訊息),服務線程會再次進入休眠狀態----直到有新的訊息到來。
    如果想要終止服務線程,在mLooper對象上調用quit(),就會退出訊息迴圈,因為線程無其他動作,所以整個線程也會終止。要注意的是當一個線程的訊息迴圈已經退出後,不能再給其發送訊息,否則會有異常拋出"RuntimeException: Handler{4051e4a0} sending message to a Handler on a dead thread"。所以,建議在Looper.prepare()後,調用Looper.myLooper()來擷取對此Looper的引用,一來是用於終止(quit()必須在對象上面調用); 另外就是用於接收訊息時檢查訊息迴圈是否已經退出(如上例)。 

 

      4、Handler

        一個Handler允許你發送和處理一個與一個線程的MessageQueue相關聯的Message和Runnable對象。每一個Handler執行個體都和一個單一線程以及這個線程的MesageQueue相關聯。當你建立一個新的Handler執行個體 ,它被綁定到建立它的線程/訊息佇列的線程——從那時起,它將處理這個MessageQueue 裡面的訊息和runnables,執行MessageQueue 面出來的訊息。它是訊息(Message)的處理者。通過Handler對象我們可以封裝Message對象,然後通過sendMessage(msg)把Message對象添加到 MessageQueue中;當MessageQueue迴圈到該Message時,就會調用該Message對象對應的handler對象的 handleMessage()方法對其進行處理。由於是在handleMessage()方法中處理訊息,因此我們應該編寫一個類繼承自 Handler,然後在handleMessage()處理我們需要的操作。
                               
           對於Handler來說,主要有兩個功能:1、計劃messages and runnables在將來某個時刻被執行 2、將一個要在其他線程執行的動作放入到隊列裡面。handler扮演了往MQ上添加訊息和處理訊息的角色(只處理由自己發出的訊息),即通知MQ它要執行一個任務(sendMessage),並在loop到自己的時候執行該任務(handleMessage),整個過程是非同步。handler建立時會關聯一個looper,預設的構造方法將關聯當前線程的looper,不過這也是可以set的.android的主線程也是一個looper線程(looper在android中運用很廣),我們在其中建立的handler預設將關聯主線程MQ。因此,利用handler的一個solution就是在activity中建立handler並將其引用傳遞給worker thread,worker thread執行完任務後使用handler發送訊息通知activity更新UI。(過程)。

                           

          

import android.os.Message;public class SonThread extends Thread { private int i = 0; @Override public void run() {  while (i < 100) {   i = i + 10;   Message msg = new Message();   msg.arg1 = i;   try {    Thread.sleep(1000);   } catch (InterruptedException e) {    e.printStackTrace();   }   HandlerTestActivity.myHandler.sendMessage(msg);  }  if (i == 100) {   HandlerTestActivity.myHandler.removeCallbacks(this);  } }}import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.ProgressBar;public class HandlerTestActivity extends Activity { private ProgressBar progressBar; private SonThread myThread; public static Handler myHandler; public void init() {  progressBar = (ProgressBar) findViewById(R.id.progressBar1);  myThread = new SonThread();  myThread.start();  myHandler = new Handler() {   @Override   public void handleMessage(Message msg) {    super.handleMessage(msg);    progressBar.setProgress(msg.arg1);   }  }; } @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  init(); }}

 

 

          

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.