当活动暂停时,定时器功能是否会自动停止?

时间:2011-08-24 00:43:18

标签: android timer activity-lifecycle

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

如果它在暂停时运行,我该如何阻止它?

梅尔。

在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

2 个答案:

答案 0 :(得分:2)

在这种情况下,您应该将Timer对象实现为活动的实例成员,在活动的onResume()方法中创建并启动它,并在onPause()方法中停止它那项活动;这样它只有在活动位于前台时才会运行。

答案 1 :(得分:1)

在大多数情况下,当Activity在后台时,线程会继续执行。系统保留随时终止活动及其相关流程的权利。有关详细信息,请参阅开发指南中的Managing the Activity Lifecycle

相关问题