4

我有一个计时器,它使功能每分钟运行一次。当活动暂停时,计时器将继续运行。我不希望它运行,因为它是不必要的。

如果它在暂停时确实运行,我该如何防止它?

梅尔。

在 onCreate() 我有

//Respond to clock changing every minute, on the minute
    myTimer = new Timer();
    GregorianCalendar calCreationDate = new GregorianCalendar();
    calCreationDate.add(Calendar.MILLISECOND,  (-1*calCreationDate.get(Calendar.MILLISECOND)));
    calCreationDate.add(Calendar.SECOND, -1*calCreationDate.get(Calendar.SECOND));
    calCreationDate.add(Calendar.MINUTE, 1);

    //Update every one minute
    myTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            timerMethod();  
        }
    }, calCreationDate.getTime(), 60000);

在课堂上(在 onCreate() 之外)我有:

//Update the clock every minute
protected void timerMethod() {
    this.runOnUiThread(Timer_Tick);
}  //end TimerMethod


private Runnable Timer_Tick = new Runnable() {
    public void run() {
        int intTpHour = tpTimePicker.getCurrentHour();
        int intTpMinute = tpTimePicker.getCurrentMinute();

        displayMyTime(intTpHour, intTpMinute);
    }
};  //end Runnable Timer Tick
4

2 回答 2

2

In that case you should implement your Timer object as an instance member of your activity, create and start it in the onResume() method of your activity and stop it in the onPause() method of that activity ; that way it will be running only when the activity is in the foreground.

于 2011-08-24T00:55:24.217 回答
1

在大多数情况下,当 Activity 处于后台时,线程会继续执行。系统保留随时终止Activity及其相关进程的权利。有关详细信息,请参阅开发指南中的管理活动生命周期。

于 2011-08-24T00:53:17.897 回答