在开发“戎码”APP的过程中,需要用到一个计时的功能。在查阅了相关资料和API后,决定使用TimerTask来实现这个功能。
需求: 在界面上有一个TextView,用来计时。
Timer 和 TimerTask的使用:
TimerTask其实也是继承自Runnable接口的.,因此,也就相当于多开了一个线程,在固定的时间间隔,运行一次。
1.创建TimerTask的实例:
TimerTask task = new TimerTask()
{
public void run()
{
//要执行的内容
//我在这里是创建了一个Message对象,用于通知主线程修改UI
Message msg = new Message();
msg.what = 0x1;
handler.sendMessage(msg);
}
};
2.通过Timer启动线程:
Timer timer= new Timer();
timer.schedule(task,1000,1000);
//第一个参数:启动的task
//第二个参数:延迟启动的时间
//第三个参数:每隔多长时间启动一次
3.调用handleMessage()来修改UI,创建一个int类型的i,每秒自增1.
if(msg.what == 0x1)
{
i++;
int hour = i/3600;
int minute = i/60%60;
int second = i%60;
//此处将会获得已经过的小时、分钟、秒,如果数字小于10,则在数字前面加“0”
String hourText = toText(hour);
String minuteText = toText(minute);
String secondText = toText(second);
mTv.setText(hourText+":"+minuteText+":"+secondText);
}
public String toText(int number)
{
if(number < 10)
{
return "0"+number;
}
else
{
return Integer.toString(number);
}
}