Android中的Timer一般像下面这样写:
Timer timer = new Timer( ); TimerTask task = new TimerTask( ) { public void run ( ) { Message message = new Message( ); message.what = 1; handler.sendMessage(message); } }; final Handler handler = new Handler( ) { public void handleMessage(Message msg) { switch (msg.what) { case 1: log.e("Timer","Timer"); update( ); break; } super.handleMessage(msg); } }; protected void onDestroy ( ) { if (timer != null) { timer.cancel( ); timer = null; } super.onDestroy( ); } protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); timer.schedule(task,1000,5000); }
最重要的一点是 timer.schedule(task,1000,5000),如果设置为 timer.schedule(task,5000)是不会工作的。
因为timer.schedule(task,5000) 是表示执行一次的任务。
timer.schedule(task,1000,5000)表示 1 秒钟后开始 5 秒钟为周期 重复执行,
更好的方法是通过下面的代码 (Handler加Runnable线程,更简洁)
private Handler handler = new Handler( ); private Runnable runnable = new Runnable( ) { public void run ( ) { update( ); handler.postDelayed(this,1000); //postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中 } }; handler.postDelayed(runnable,1000); // 开始Timer handler.removeCallbacks(runnable); //停止Timer
本文结束