I have a timer that causes a function to run every minute, on the minute. When the activity is paused will the timer continue to run. I dont want it to run as it is unecessary.

If it does run when paused, how can I prevent it?

Mel.

In onCreate() I have

//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);

Within the class (outside of onCreate()) I have:

//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
有帮助吗?

解决方案

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.

其他提示

Under most circumstances threads continue to execute when an Activity is in the background. The system reserves the right to kill the Activity and its related process at any time. See the Managing the Activity Lifecycle in the Dev Guide for more details.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top