效果:
在界面中每秒刷新时间
关键代码如下:
public static TimerHandler timerHandler; //定义一个TimerHandler全局变量
在onCreate函数中
timerHandler = new TimerHandler(); //实例化TimerHandler
Timer timer = new Timer(); //设置定时器Timer
timer.schedule(new MyTimerTask(), 0, 1000 ); //0表示无延迟,1000表示隔1000ms
private class MyTimerTask extends TimerTask
{
public void run()
{
MainActivity.timerHandler.sendEmptyMessage(0);
}
}
public class TimerHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date=new Date();
Date date2 = date;
try {
date2 = sdf.parse(START_DATE);<span style="white-space:pre"> </span>//START_DATE是自己定义的一个代表日期的字符串全局变量
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int secondNum=(int)(((date.getTime()-date2.getTime())/(1000))%60);
int minNum = (int)(((date.getTime()-date2.getTime())/(60*1000))%60);
int hourNum = (int)(((date.getTime()-date2.getTime())/(60*60*1000))%24);
int dayNum=(int)((date.getTime()-date2.getTime())/(24*60*60*1000));
MainActivity.day.setText(""+dayNum);
MainActivity.hour.setText(""+hourNum);
MainActivity.min.setText(""+minNum);
MainActivity.second.setText(""+secondNum);
}
}