2011-08-24 38 views
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 

回答

2

在這種情況下,你應該實現你Timer對象爲您的活動的一個實例成員,創建並在活動onResume()方法來啓動它,並在該活動的onPause()方法阻止它;這樣它只會在活動處於前臺時纔會運行。

+0

Thankyou。這對我有效。 – Mel

1

在大多數情況下,線程繼續在Activity處於後臺時執行。系統保留隨時終止活動及其相關過程的權利。有關更多詳細信息,請參閱開發指南中的Managing the Activity Lifecycle