android Timer使用方法
Timer属性:http://www.apihome.cn/api/java/Timer.html
声明创建:
1 private Timer mTimer; 2 3 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 this.setContentView(R.layout.main); 7 8 timer = new Timer(); 9 timer.schedule(task, 1000, 5000); 11 } 13 14 TimerTask task = new TimerTask() { 15 @Override 16 public void run() { 18 Message message = new Message(); 20 message.what = 1; 22 handler.sendMessage(message); 24 } 26 }; 27 28 final Handler handler = new Handler() { 30 public void handleMessage(Message msg) { 32 switch (msg.what) { 34 case 1: 36 log.e("Timer", "Timer"); 38 //要实现的功能代码:update(); 40 break; 42 } 44 super.handleMessage(msg); 46 } 48 }; 49 50 protected void onDestroy() { 52 if (timer != null) { 54 timer.cancel(); 56 timer = null; 58 } 60 super.onDestroy(); 62 }
最重要的一点是 timer.schedule(task,1000,5000),如果设置为 timer.schedule(task,5000)是不会工作的。
因为timer.schedule(task,5000) 是表示执行一次的任务。
timer.schedule(task,1000,5000)表示 1 秒钟后开始 5 秒钟为周期 重复执行
1 private Handler handler = new Handler( ); 2 3 private Runnable runnable = new Runnable( ) { 4 5 public void run ( ) { 6 7 update( ); 8 9 handler.postDelayed(this,1000); //postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中 10 11 } 12 13 }; 14 15 handler.postDelayed(runnable,1000); // 开始Timer 16 17 handler.removeCallbacks(runnable); //停止Timer
(转自:http://blog.csdn.net/jincf2011/article/details/6603916)