Android Handler简单使用

 1 package com.example.myhandlertest3;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.Message;
 6 import android.support.v7.app.ActionBarActivity;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 import android.widget.TextView;
11 /**
12  * Android Handler
13  * @author shaobn
14  * @date 2015/9/9
15  */
16 public class MainActivity extends ActionBarActivity {
17     private Button button;
18     private TextView tv;
19     private Handler handler; 
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         button = (Button)this.findViewById(R.id.button1);
25         handler = new Handler(){
26             
27             public void handleMessage(android.os.Message msg) {
28                 
29                 Bundle bundle = msg.getData();
30                 String data = bundle.getString("color");
31                 MainActivity.this.button.append(data);
32             };
33         };
34         final Runnable runnable = new Runnable() {
35             
36             @Override
37             public void run() {
38                 // TODO Auto-generated method stub
39                 String color = "red";
40                 Message message = new Message();
41                 Bundle bundle = new Bundle();
42                 bundle.putCharSequence("color", color);
43                 message.setData(bundle);
44                 MainActivity.this.handler.sendMessage(message);
45                 try {
46                     Thread.sleep(3000);
47                 } catch (Exception e) {
48                     // TODO: handle exception
49                     e.printStackTrace();
50                 }
51             }
52         };
53         button.setOnClickListener(new OnClickListener() {
54             
55             @Override
56             public void onClick(View arg0) {
57                 // TODO Auto-generated method stub
58                 new Thread(runnable).start();
59             }
60         });
61     }
62 
63     
64 }

自己随便写的一个demo,记录一下。

posted @ 2015-09-09 15:00  邻家小书童  阅读(158)  评论(0编辑  收藏  举报