android 使用Handler UI线程和子线程通讯 更新UI

 

 

 1 package com.act262.sockettx;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.os.Handler;
 6 import android.os.Message;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 import android.widget.EditText;
11 import android.widget.TextView;
12 
13 /**
14  * 可以在其他线程中获取View类的数据,但是不能修改或者设置View类的数据
15  * 
16  */
17 public class Main extends Activity {
18 
19     TextView result = null;
20     EditText get = null;
21     Button update = null;
22     Handler handler;
23 
24     public void onCreate(Bundle bundle) {
25         super.onCreate(bundle);
26         setContentView(R.layout.main);
27         result = (TextView) findViewById(R.id.result);
28         update = (Button) findViewById(R.id.update);
29         get = (EditText) findViewById(R.id.get);
30 
31         handler = new Handler() {
32             public void handleMessage(Message msg) {
33                 if (msg.what == 1) {
34                     result.setText("after update ui "
35                             + msg.getData().getString("data")
36                             + "  \nman thread : "
37                             + Thread.currentThread().getName());
38                 }
39             }
40         };
41 
42         result.setText("before update ui  main thread : "
43                 + Thread.currentThread().toString());
44 
45         update.setOnClickListener(new OnClickListener() {
46 
47             @Override
48             public void onClick(View v) {
49                 // TODO Auto-generated method stub
50                 new MyThread("my thread").start();
51             }
52         });
53 
54     }
55 
56     class MyThread extends Thread {
57         public MyThread(String name) {
58             super(name);
59         }
60 
61         @Override
62         public void run() {
63             // 发送不带数据的消息
64             // handler.sendEmptyMessage(1);
65 
66             // 发送附带数据的消息
67             Message msg = new Message();
68             Bundle data = new Bundle();
69             data.putString("data", get.getText().toString() + " my thread:  "
70                     + Thread.currentThread().getName());
71             msg.setData(data);
72             msg.what = 1;
73             handler.sendMessage(msg);
74         }
75     }
76 }

 

posted @ 2013-12-25 16:35  act262  阅读(291)  评论(0编辑  收藏  举报