Android中的非同步處理

來源:互聯網
上載者:User

標籤:

主要有Message,Handler,MessageQueue,Loop:

1.Message 和Handler配合使用:

Message message = new Message();message.what = UPDATE_TEXT;handler.sendMessage(message); // 將Message對象發送出去

  

private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case UPDATE_TEXT:// 在這裡可以進行UI操作text.setText("Nice to meet you");break;default:break;}}};

  Message所有的成員有

public int arg1 arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
public int arg2 arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
public Object obj An arbitrary object to send to the recipient.
public Messenger replyTo Optional Messenger where replies to this message can be sent.
public int what User-defined message code so that the recipient can identify what this message is about.

Message 是線上程之間傳遞的訊息,它可以在內部攜帶少量的資訊,用於在不同線
程之間交換資料。上一小節中我們使用到了 Message 的 what 欄位,除此之外還可以使
用 arg1 和 arg2 欄位來攜帶一些整型資料,使用 obj 欄位攜帶一個 Object 對象。
要攜帶更多資料,可以使用setData(Bundle).

2 Handler

Handler 顧名思義也就是處理者的意思,它主要是用於發送和處理訊息的。發送消
息一般是使用 Handler 的 sendMessage()方法,而發出的訊息經過一系列地輾轉處理後,
最終會傳遞到 Handler 的 handleMessage()方法中。
3 MessageQueue

MessageQueue 是訊息佇列的意思,它主要用於存放所有通過 Handler 發送的訊息。
這部分訊息會一直存在於訊息佇列中,等待被處理。每個線程中只會有一個 MessageQueue
對象。
4 Loop

Looper 是每個線程中的 MessageQueue 的管家,調用 Looper 的 loop()方法後,就會
進入到一個無限迴圈當中,然後每當發現 MessageQueue 中存在一條訊息,就會將它取
出,並傳遞到 Handler 的 handleMessage()方法中。每個線程中也只會有一個 Looper 對象。

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.