一个简单的计时器

果然是新手啊,现在的阶段是什么都要上网查,只知道实现原理,demo却写不出来。哎

第一个练手的,一个简单的计时器,基本原理时使用线程控制textview的定时刷新

View Code
 1 package king.timer;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.os.Handler;
6 import android.os.Message;
7 import android.util.Log;
8 import android.view.View;
9 import android.widget.Button;
10 import android.widget.TextView;
11
12 public class TimerActivity extends Activity {
13 private static final String TAG = "TimerActivity";
14 private Button startBtn,stopBtn;
15 private Boolean flag = false;
16 private Thread tThread = null;
17 private final int time = 2*1000;
18 public TextView showResult;
19 private Handler thandler;
20 private int count = 0;
21 @Override
22 public void onCreate(Bundle savedInstanceState) {
23 tThread = new Thread(new tRunnable());
24 super.onCreate(savedInstanceState);
25 setContentView(R.layout.main);
26 thandler = new TimerHandler();
27 showResult = (TextView)findViewById(R.id.showResult);
28 startBtn = (Button)findViewById(R.id.startBtn);
29 startBtn.setOnClickListener(new View.OnClickListener() {
30
31 public void onClick(View v) {
32 // TODO Auto-generated method stub
33 flag = true;
34 if(!tThread.isAlive()){
35 tThread.start();
36 }
37 }
38 });
39 stopBtn = (Button)findViewById(R.id.stopBtn);
40 stopBtn.setOnClickListener(new View.OnClickListener() {
41
42 public void onClick(View v) {
43 // TODO Auto-generated method stub
44 flag = false;
45 }
46 });
47 }
48 class tRunnable implements Runnable{
49
50 public void run() {
51 // TODO Auto-generated method stub
52 while(true){
53 if(flag){
54 try {
55 Thread.sleep(time);
56 thandler.obtainMessage(0, "刷新次数:"+count).sendToTarget();
57 count++;
58 } catch (InterruptedException e) {
59 // TODO Auto-generated catch block
60 e.printStackTrace();
61 }
62 }
63 }
64 }
65
66 }
67 class TimerHandler extends Handler{
68 public void handleMessage(Message message){
69 Log.v(TAG, "show"+count);
70 showResult.setText(message.obj.toString());
71 }
72 }
73 }

posted @ 2011-07-29 10:52  傲视温柔  阅读(140)  评论(0编辑  收藏  举报