1 package com.hyzhou.timerdemo1; 2 3 import java.util.Timer; 4 import java.util.TimerTask; 5 6 import android.os.Bundle; 7 import android.os.Handler; 8 import android.os.Message; 9 import android.util.Log; 10 import android.view.View; 11 import android.view.View.OnClickListener; 12 import android.widget.Button; 13 import android.widget.TextView; 14 import android.app.Activity; 15 16 public class MainActivity extends Activity { 17 18 // 定义计时器 19 Timer timer=new Timer(); 20 21 private TextView tv; 22 private Button bt; 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 //定义UI组件 29 tv=(TextView)findViewById(R.id.tv); 30 bt=(Button)findViewById(R.id.bt); 31 32 Log.i("hyzhou", Thread.currentThread().getName()); 33 //定义Handler 34 final Handler handler=new Handler(){ 35 36 @Override 37 public void handleMessage(Message msg) { 38 // TODO Auto-generated method stub 39 super.handleMessage(msg); 40 //handler处理消息 41 if (msg.what>0) { 42 tv.setText(" "+msg.what); 43 } 44 else { 45 //在handler里可以更改UI组件 46 tv.setText("开始点火"); 47 timer.cancel(); 48 } 49 } 50 51 }; 52 // 定义按钮的点击监听器 53 bt.setOnClickListener(new OnClickListener() { 54 55 @Override 56 public void onClick(View v) { 57 // TODO Auto-generated method stub 58 timer.schedule(new TimerTask() { 59 int i=10; 60 // TimerTask 是个抽象类,实现的是Runable类 61 @Override 62 public void run() { 63 // TODO Auto-generated method stub 64 Log.i("hyzhou", Thread.currentThread().getName()); 65 //定义一个消息传过去 66 Message message=new Message(); 67 message.what=i--; 68 handler.sendMessage(message); 69 } 70 }, 1000, 2000); 71 } 72 }); 73 74 } 75 76 }
参考:http://www.360doc.com/content/11/1129/15/6541311_168365884.shtml