java timer 使用:

在看starup_timer 的开源代码 看到timer的使用的地方 想写一片日志 结果发现有人早写了关于这个地方 故引用:

引用自:http://www.cnblogs.com/keyindex/articles/1824794.html

前言

  学习android一段时间了,为了进一步了解android的应用是如何设计开发的,决定详细研究几个开源的android应用。从一些开源应用中吸收点东西,一边进行量的积累,一边探索android的学习研究方向。这里我首先选择了jwood的 Standup Timer 项目。

Timer

  如果需要定期执行某些任务,可以使用Timer 类,它接受一个TimerTask用于指示需要执行的操作。Timer会在后台开一个线程来进行定期任务处理。在Standup Timer 中使用它来计时,其实在本系列文章中的上一篇:android的Handler 就已经使用了Timer。下面我们来看看Standup Timer里相关的代码:
Timer
private void startTimer() {
Logger.d(
"Starting a new timer");
timer
=new Timer();
TimerTask updateTimerValuesTask
= new TimerTask()
{

@Override
public void run() {
updateTimerValues();

}

};
timer.schedule(updateTimerValuesTask,
1000, 1000);

}
updateTimerValues
protected synchronized void updateTimerValues()
{
currentIndividualStatusSeconds
++;
if (remainingIndividualSeconds > 0)
{
remainingIndividualSeconds
--;
if (remainingIndividualSeconds == warningTime)
{
Logger.d(
"Playing the bell sound");
if (SettingActivity.playSounds(this)) {
//如果等于设定的警告时间且设置允许警告则播放警告铃声
playWarningSound();
}
//if
} else {
if (remainingIndividualSeconds == 0) {
Logger.d(
"Playing the airhorn sound");
if (SettingActivity.playSounds(this)) {
//如果时间等于零,切允许铃声提醒,则播放结束铃声
playFinishedSound();
}
//if
}//if
}//else
}//if



if (remainingMeetingSeconds > 0)
remainingMeetingSeconds
--;

//使用Handler更新UI
updateDisplayHandler.sendEmptyMessage(0);
}
在startTimer方法里生成了一个新的Timer 并通过内部类的方式 生成一个 TimerTask ,通过schedule()方法 指定updateTimerValuesTask 每个一秒运行。
最后onResume中指定startTimer运行
@Override
protected void onResume()
{
super.onResume();
acquireWakeLock();
startTimer();
}

timer extends thread  从而在timertask 的run中call method 要使用 线程安全的东西

自己在使用Timer的时候要这样进行定义

 private void testTimer()
    {
     //
     myTimer = new Timer();
     myTimer.schedule(new mytask(), 1000, 2000);
    }
   
    class mytask extends TimerTask
    {

  @Override
  public void run() {
   // TODO Auto-generated method stub
   System.out.println("this is timer test");
   //if you implents method here must synchronized. make sure safe thread
   
  }
     //
    }

如果想通过timer来改变android中UI的东西 因为在Android中并必须使用主线程进行UI的更新 从而需要给主线程的Handle.sendMessage 利用Message 来进行相应的信息的传递。

原文地址:https://www.cnblogs.com/fwycmengsoft/p/2262774.html