2012-02-28 28 views
3

我正在設計一個倒數計時器,它完美的工作,但只有如果我留在這Activity。因爲,如果倒計時開始,我回頭舉例並開始其他Activity,countdonws繼續倒計時。從邏輯上講,如果我重新開始倒數計時器的活動,看起來好像什麼都沒有倒計時,但在免費倒計時,我知道,因爲在定時器的開始,我會發出一個繼續通知,以顯示它在通知選項卡。在不同的活動中捕捉倒數計時器

代碼如下,sendnotification方法是在時間結束時拋出警報的方法,並且每秒向該選項卡發送通知以顯示在頂部。

public static final int NOTIFICATION_ID = 33; 
public static final int NOTIFICATION_ID_Tiempo = 34; 
private int minCrono; 
TextView text; 
MyCounter timer; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 


    StartCrono = (Button) findViewById(R.id.butt_start); 
    CancelCrono = (Button) findViewById(R.id.butt_cancel); 
    text=(TextView)findViewById(R.id.text_countTime1); 

    CancelCrono.setEnabled(false); 


    minCrono = mins.getCurrentItem(); 

    StartCrono.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      minCrono=(60000*minCrono);  
      timer = new MyCounter(minCrono,1000); 
      timer.start(); 
     } 
    }); 

    CancelCrono.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      timer.cancel();  
      text.setText("El tiempo se ha cancelado"); 
      minutosCrono = mins.getCurrentItem(); 

      if (mNotificationManager != null) 
       mNotificationManager.cancel(NOTIFICATION_ID_Tiempo); 

     }   
    }); 
} 

倒計時類:

public class MyCounter extends CountDownTimer{   
    public MyCounter(long millisInFuture, long countDownInterval) {  
     super(millisInFuture, countDownInterval);   
    } 
    @Override 
    public void onFinish() { 

     StartCrono.setEnabled(true); 
     CancelCrono.setEnabled(false); 
     mins.setEnabled(true); 
     minCrono = mins.getCurrentItem(); 
     // 

     text.setText("Time Complete!"); 

     sendnotification("Guau", "Time finished."); 

    } 
    @Override 
    public void onTick(long millisUntilFinished) { 
     long segRestantesTotal=(millisUntilFinished/1000); 
     long minRestantes= (segRestantesTotal/60); 
     long segRestantes= (segRestantesTotal%60); 


     if(segRestantes>=10){ 
      text.setText(minRestantes+":"+segRestantes); 
      sendnotificationTiempo("Guau", minRestantes+":"+segRestantes); 
     } 
     else{ 
      text.setText(minRestantes+":0"+segRestantes); 
      sendnotificationTiempo("Guau", minRestantes+":0"+segRestantes); 
     } 
    } 
} 

}

所以我會做的,就是知道我什麼時候回去Activity,我開始一個又一個,來顯示時間是什麼倒計時在後臺顯示,例如在textview中顯示。

或者,如果我可以從通知選項卡倒計時完美的時間。 謝謝!

回答

0

將您的MyCounter實例移出活動。當活動重新啓動時,實例正在被重新創建,所以舊的不在了。有幾種方法可以做到這一點,但是您需要讓MyCounter實例存在於Activity可以訪問的地方,但不負責其生命週期。我使用了我寫的一個基本的ServiceLocator實現,但是您可以輕鬆創建一個自定義的Application類,並在那裏保留定時器(或創建和控制定時器的控制器類)。

+0

buff我失去了!我可以在通知欄中顯示時間嗎?因爲每一秒都在倒計時 – Txispas 2012-02-28 18:25:37