【问题标题】:Do timer functions automatically stop when an activity is paused?活动暂停时计时器功能会自动停止吗?
【发布时间】:2011-08-24 00:43:18
【问题描述】:

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

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

梅尔。

在 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

【问题讨论】:

    标签: android timer activity-lifecycle


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-11-01
        • 1970-01-01
        • 2013-12-31
        • 1970-01-01
        • 2016-11-05
        • 2014-04-17
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多