2013-03-15 101 views
14

我的Android應用程序中有一個動畫,它使TextView呈現不同的顏色。我使用了TimerTask,Timer和Runnable方法來實現這一點。我需要做的就是當用戶在onPause()這個動畫中離開應用程序時停止線程,並在用戶返回到onResume()中的應用程序時恢復線程。以下是我實現的代碼,但它不工作(onPause()和onResume()件),我不明白爲什麼。我已經閱讀了其他一些關於類似問題的文章,但他們並沒有幫助我找出在我的情況下做什麼。我讀過TimerTasks已經過時了,我應該使用一個ExecutorService方法;我不清楚如何實現這個功能。如何暫停和恢復TimerTask /定時器

...timerStep5 = new TimerTask() { 

     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
       if (b5) { 
        cashButton2SignalText.setBackgroundColor(Color.RED); 
        cashButton2SignalText.setTextColor(Color.WHITE); 
        b5=false; 
       } else { 
        cashButton2SignalText.setBackgroundColor(Color.WHITE); 
        cashButton2SignalText.setTextColor(Color.RED); 
        b5=true; 
       } 
       } 
      }); 
     } 
}; 

timer5.schedule(timerStep5,250,250); 

} 

public void onPause(){ 

    super.onPause(); 

    timerStep5.cancel(); 

} 

public void onResume(){ 

    super.onResume(); 

    timerStep5.run(); 

} 
+0

[暫停/停止和啓動/恢復持續的Java的TimerTask?]的可能的複製(http://stackoverflow.com/questions/2098642/pausing-stopping-and-starting-resuming-java-timertask-continuously ) – Gboy 2017-02-11 12:29:12

回答

12

TimerTask被取消,不能再運行,你必須創建一個新的實例。

閱讀細節在這裏:

https://stackoverflow.com/a/2098678/727768

ScheduledThreadPoolExecutor推薦用於新的代碼,它處理的情況下,像異常和任務採取更長的時間比預定的時間間隔。

但是對於你的任務,TimerTask應該足夠了。

+0

好吧,我之前看到這篇文章,並且很困惑,也許你可以爲我澄清一些事情:用戶可能會在TimerTask活動期間離開我的應用程序,並且多次返回該活動。那不是說我每次用戶離開時都會在onResume()中創建一個TimerTask的新實例,並返回? – embersofadyingfire 2013-03-16 04:18:45

+0

問題:如果我忽略用戶離開此活動一段時間並返回的操作,並忽略用於暫停和恢復TimerTask的任何實現,但實現onStop()以在用戶最終前進到時取消TimerTask另一個活動,當TimerTask活動暫停時這會導致某種內存泄漏嗎? – embersofadyingfire 2013-03-16 05:57:06

+1

我不認爲會有任何內存泄漏,但沒有任何意義讓你的UI更新任務在後臺運行。是的,你應該即時創建TimerTask,它不可重用。它是這樣設計的。 (我猜爲線程安全)onResume也不是一些緊密的循環,創建對象的成本可以忽略不計。 – 2013-03-16 06:59:09

2

下面是我做到的。添加pauseTimer布爾值,在那裏暫停發生(也許按鈕偵聽器),並且如果爲真,則不計數定時器。

private void timer(){ 
    Timer timer = new Timer(); 
    tv_timer = (TextView) findViewById(R.id.tv_locationTimer); 
    countTimer = 0; 
    timer.scheduleAtFixedRate(new TimerTask() { 
     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        String s_time = String.format("%02d:%02d:%02d", 
          countTimer/3600, 
          (countTimer % 3600)/60, 
          countTimer % 60); 
        tv_timer.setText(s_time); 
        if (!pauseTimer) countTimer++; 
       } 
      }); 
     } 
    }, 1000, 1000); 
}