简述:这是一类定时功能的原型,用来在后台线程中运行一些定时的服务,比如定时修改时间
知识点:
1. Android多线程的消息通信(handler)
2. Java中时间的获取,以及String的格式化(SimpleDateFormat)
3. Android PostDelay 的定期的实现
4. timertask实现定期更新
在这里我们就对于handler的方法,开一个新的Thread每隔3秒, 用来定时修改一个TextView的时间。对于timertask,道理也是一样的,调用schedule方法,每隔三秒更新一次。
1.使用handler的方法:
protected void updateClock2Time(boolean isChecked)
{
if (isChecked) {
updateCurrentTime = new Thread() {
@Override
public void run()
{
SimpleDateFormat formatter = new SimpleDateFormat(
"HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String currentTime = formatter.format(curDate);
message = handler.obtainMessage(UPDATE_MY_TV, currentTime);
handler.sendMessage(message);
// use Handler to control the time
handler.postDelayed(this, );
}
};
updateCurrentTime.start();
} else {
handler.removeCallbacks(updateCurrentTime);
}
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg)
{
switch (msg.what) {
case UPDATE_MY_TV:
String currentTime = (String) msg.obj;
clock2.setText("Current Time: " + currentTime);
break;
}
}
};
2.使用timertask的方法:
class MyTimerTask extends TimerTask
{
@Override
public void run()
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
cTime = format.format(date);
messageHandler.sendMessage(messageHandler.obtainMessage());
}
};
private Handler messageHandler = new Handler() { @Override
public void handleMessage(Message msg)
{
clock1.setText("Current Time: " + cTime);
super.handleMessage(msg);
}
};
protected void updateClock1Time(boolean isChecked)
{
if (isChecked) {
timer = new Timer();
MyTimerTask task = new MyTimerTask();
timer.schedule(task, , );
} else {
timer.cancel();
}
}