原文:http://blog.csdn.net/vrix/article/details/6337589
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(); }
最重要一点是timer.schedule(task, 1000, 5000);如果设置为timer.schedule(task, 5000)是不会工作的。
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); timer.schedule(task, 1000, 5000); }
但更好的方法是通过下面的代码
private Handler handler = new Handler(); private Runnable runnable = new Runnable() { public void run() { update(); handler.postDelayed(this, 1000); } };
开始Timer
handler.postDelayed(runnable, 1000);
停止Timer
handler.removeCallbacks(runnable);