Android開發——訊息處理傳遞機制

來源:互聯網
上載者:User

標籤:android   style   blog   color   io   os   ar   sp   資料   

在程式開發時,對於比較耗時的操作,通常會為其開闢一個單獨的線程來執行,以儘可能減少使用者的等待時間。在Android中,預設情況下,所有的操作都是在主線程中進行的,主線程負責與UI相關的事件。而在自己建立的線程中,不能對UI進行操作。因此Android提供了訊息處理傳遞機制來解決這一問題。

Message,訊息類。存放於MessageQueue中,包含資料類型,使用者自訂的訊息代碼等。

MessageQueue,訊息佇列。在MessageQueue中,存放的訊息按照FIFO(先進先出)的原則執行。

Handler,訊息發送類。發送或者處理Message對象到所線上程的MessageQueue中。

Looper,迴圈者。用來迴圈讀取存放於MessageQueue中的訊息。一個線程對應一個Looper,一個Looper對象對應一個MessageQueue。Android中新增的線程是沒有開啟訊息迴圈的,但是主線程除外。系統自動為主線程建立Looper對象。

一:在非主線程中建立Looper

class LooperThread extends Thread {      public Handler mHandler;//聲明一個Handler對象               public void run() {          Looper.prepare(); //初始化Looper對象                   mHandler = new Handler() {              public void handleMessage(Message msg) { //重寫方法     // process incoming messages here              }          };          Message m=mHandler.obtainMessage();//擷取一個訊息          m.what=0x11;設定Message的what屬性的值          mHandler.sendMessage();//發送訊息                   Looper.loop();//啟動Looper      }}

二:一個打地鼠遊戲

public class MainActivity extends Activity {  private int i = 0; // 記錄其打到了幾隻地鼠  private ImageView mouse; // 聲明一個ImageView對象  private Handler handler; // 聲明一個Handler對象  public int[][] position = new int[][] { { 231, 325 }, { 424, 349 },      { 521, 256 }, { 543, 296 }, { 719, 245 }, { 832, 292 },      { 772, 358 } }; // 建立一個表示地鼠位置的數組     @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    mouse = (ImageView) findViewById(R.id.imageView1); // 擷取ImageView對象    mouse.setOnTouchListener(new OnTouchListener() {         @Override      public boolean onTouch(View v, MotionEvent event) {        v.setVisibility(View.INVISIBLE); // 設定地鼠不顯示        i++;        Toast.makeText(MainActivity.this, "打到[ " + i + " ]只地鼠!",            Toast.LENGTH_SHORT).show(); // 顯示訊息提示框        return false;      }    });       handler = new Handler() {      @Override      public void handleMessage(Message msg) {        int index = 0;        if (msg.what == 0x101) {          index = msg.arg1; // 擷取位置索引值          mouse.setX(position[index][0]); // 設定X軸位置          mouse.setY(position[index][1]); // 設定Y軸位置          mouse.setVisibility(View.VISIBLE); // 設定地鼠顯示        }        super.handleMessage(msg);      }       };    Thread t = new Thread(new Runnable() {         @Override      public void run() {        int index = 0; // 建立一個記錄地鼠位置的索引值        while (!Thread.currentThread().isInterrupted()) {          index = new Random().nextInt(position.length); // 產生一個隨機數          Message m = handler.obtainMessage(); // 擷取一個Message          m.what = 0x101; // 設定訊息標識          m.arg1 = index; // 儲存地滑鼠位置的索引值          handler.sendMessage(m); // 發送訊息             try {            Thread.sleep(new Random().nextInt(500) + 500); // 休眠一段時間          } catch (InterruptedException e) {            e.printStackTrace();          }           }         }       });    t.start(); // 開啟線程     }   }

 

Android開發——訊息處理傳遞機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.