2012-08-07 58 views
1

如何有效地讓應用程序停止時在後臺運行計時器?儀式現在我沒有做任何事情,計時器將繼續運行,當應用程序已經停止,但有些時候它會停止運行,沒有我給它的命令。 這就是我如何運行目前我的定時器:如何在後臺運行計時器

if(t == null){ 
    t = new Timer(); 
    t.schedule(new TimerTask() { 

     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 

       public void run() { 
        if(DHPDPS==0){ 
         money = (DPPS+Reserve); 
         Reserve = (money); 
         String end = String.format("%1f", money); 
         t1.setText("$" + end); 
        }else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){ 
         money = (DOTPPS+Reserve); 
         Reserve = (money); 
         String end = String.format("%1f", money); 
         t1.setText("$" + end); 
        } else{ 

         money = (DPPS+Reserve); 
         Reserve = (money); 
         String end = String.format("%1f", money); 
         t1.setText("$" + end); 
        } 
        counter++; 
        //if(counter == 3000) 
        // t.cancel(); 

        // Display pay per second 
        if(counter <= DHPDPS || DHPDPS == 0){ 
        t2.setText("Your pay per second is: $"+result); 
        }else{ 
         t2.setText("Your pay per second is: $"+result2); 
        } 
       } 
      }); 
     } 
    }, 20, 20); 

它在OnCreate()宣佈,謝謝!

回答

3

對於在後臺運行的任務,您應該使用IntentService。即使您的活動被操作系統暫停或刪除,它也會繼續運行。

+0

你能告訴我一個我如何使用IntentService的例子嗎?我從來沒有處理過他們 – Hockeyman271 2012-08-07 23:20:32

+1

http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/ – Quinma 2012-08-07 23:24:02

+1

那麼通過谷歌搜索「android intentservice示例」,你應該找到很多。這很簡單:只需擴展IntentService並覆蓋1或2個方法,在這些方法中,您可以執行之前在其他地方所做的工作。然後使用startService()方法和IntentService的類從您的活動中啓動服務。 – kgautron 2012-08-07 23:25:25

0

如果您的手機內存開始填滿,它將關閉所有未被使用的活動。

對於像計時器這樣的事情來說,將開始時間保存到SQLite中以及重新加載活動時可能會更好,並將其作爲計算持續時間的起點。

否則,如果您的意圖是定時器不停地滴答作響,將其轉化爲意向服務。

相關問題