Android 主線程和線程之間相互發送訊息

來源:互聯網
上載者:User

通過分析Activity源碼,我們知道每個Activity都有一個Looper,所以主線程在接收Message是不需要調用Looper.prepare()和Looper.loop(),但是線程是不帶Looper的,當線程要接收來自主線程的訊息是就需要調用Looper.prepare()和Looper.loop()。以下我們將通過一個樣本,講述主線程和線程之間如何發送Message。
 

01 import android.app.Activity;

02 import android.os.Bundle;

03 import android.os.Handler;

04 import android.os.Message;

05 import android.widget.Toast;

06  

07 /**

08  * 這個類是主線程,它每隔兩秒就發送一個Message給線程,線程收到Message後將發送一個Message給主線程,主線程收到Message後會將Message內容Toast出來。

09  * org.fneg.HandlerTestActivity.java

10  * Create at: 2012-6-4 下午9:39:19

11  * @author:feng

12  * Email:fengcunhan@gmail.com

13  *

14  */

15 public class HandlerTestActivity extends Activity {

16     private Handler uiHandler;

17     private ThreadWithLooper thread;

18     private Runnable showRunable;

19     @Override

20     public void onCreate(Bundle savedInstanceState) {

21         super.onCreate(savedInstanceState);

22         setContentView(R.layout.main);

23         uiHandler=new Handler(){

24             @Override

25             public void handleMessage(Message msg) {

26                 switch(msg.what){

27                 case Messages.MSG_HELLO:

28                      Toast.makeText(HandlerTestActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();

29                     break;

30                      

31                 }

32             }

33         };

34         thread=new ThreadWithLooper(uiHandler);

35          

36         thread.start();

37         showRunable=new Runnable() {

38              

39             @Override

40             public void run() {

41                 //給線程發送一個Message

42                 thread.getHandler().sendEmptyMessage(Messages.MSG_HELLO);

43                 uiHandler.postDelayed(this, 2*1000);

44             }

45         };

46         uiHandler.post(showRunable);

47          

48     }

49      

50     @Override

51     protected void onStop() {

52         super.onStop();

53         uiHandler.removeCallbacks(showRunable);

54     }

55 }


01 import android.os.Handler;

02 import android.os.Looper;

03 import android.os.Message;

04  

05 /**

06  * 從線程發送訊息到UI線程(主線程)

07  * org.fneg.ThreadWithLooper.java

08  * Create at: 2012-6-4 下午4:58:11

09  * @author:feng<br/>

10  * Email:fengcunhan@gmail.com

11  *

12  */

13 public class ThreadWithLooper extends Thread {

14     private Handler handler;

15      

16     private Handler uiHandler;

17      

18     public ThreadWithLooper(Handler mHandler){

19         this.uiHandler=mHandler;

20         //初始化Handler,接收到主線程發送過來的Message就回複一個Message給主線程,訊息內容是 一個字串和目前時間

21         handler =new Handler(){

22  

23             @Override

24             public void handleMessage(Message msg) {

25                 switch(msg.what){

26                 case Messages.MSG_HELLO:

27                      Message message=new Message();

28                      message.what=Messages.MSG_HELLO;

29                      message.obj="Yes!I get a hello"+System.currentTimeMillis();

30                      uiHandler.sendMessage(message);

31                     break;

32                      

33                 }

34             }

35              

36         };

37     }

38      

39     public Handler getHandler() {

40         return handler;

41     }

42  

43     public void setHandler(Handler handler) {

44         this.handler = handler;

45     }

46      

47     @Override

48     public void run() {

49         Looper.prepare();

50          

51         Looper.loop();

52     }

53      

54      

55 }


01 /**

02  *

03  * org.fneg.Messages.java

04  * Create at: 2012-6-4 下午4:51:20

05  * @author:feng

06  * Email:fengcunhan@gmail.com

07  *

08  */

09 public class Messages {

10    public static final int MSG_HELLO=0X1;

11 }


 

相關文章

聯繫我們

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