弃用的方法
网上搜索有介绍使用Sleep
方法实现的,这里就不介绍了
1/3. 在 Activity 中声明成员变量
Handler handler=new Handler();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Runnable runnable=new Runnable() { @Override public void run() { Log.i(TAG,sdf.format(System.currentTimeMillis())); handler.postDelayed(this, 2000); }};
2/3. 启动定时器
handler.postDelayed(runnable,1000);//每两秒执行一次runnable.
3/3. 关闭定时器
handler.removeCallbacks(runnable);
解释
启动定时器中的 1000
表示点击按钮1秒钟后启动定时器runnable
中的 2000
表示每2秒钟执行一次