android Handler消息通信

 1 package com.example.testhandler;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.Message;
 6 import android.app.Activity;
 7 import android.view.Menu;
 8 import android.widget.TextView;
 9 
10 public class MainActivity extends Activity {
11 
12     Handler handler = null;
13     String textString = null;
14     TextView textView;
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19         textView = (TextView) findViewById(R.id.text);
20         Runnable task = new Runnable() {
21             
22             @Override
23             public void run() {
24                 textString = "Hello World!";
25                 Message msg = new Message();
26                 msg.what = 0x123;
27                 handler.sendMessage(msg);
28             }
29         };
30         handler = new Handler(){
31 
32             @Override
33             public void handleMessage(Message msg) {
34                 //super.handleMessage(msg);
35                 if (msg.what == 0x123) {
36                     textView.setText(textString);
37                 }
38             }
39             
40         };
41         
42         new Thread(task).start();
43         
44     }
45 
46     @Override
47     public boolean onCreateOptionsMenu(Menu menu) {
48         // Inflate the menu; this adds items to the action bar if it is present.
49         getMenuInflater().inflate(R.menu.main, menu);
50         return true;
51     }
52 
53 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。