2014-09-05 84 views
1

我在Android應用程序中遇到了一個奇怪的行爲。 我想安排一個固定費率的操作來保存「玩家」對象的屬性。在應用程序流程中,用戶可以更改它的設置,但通過這個小任務每2分鐘執行一次保存。當應用程序處於後臺(並處於「發佈」模式)時,scheduleAtFixedRate()不起作用

的任務是通過靜態ScheduledExecutorService運行,當應用程序啓動時初始化:

private static ScheduledExecutorService threadExecutor; 

//... 

public static void initialize() 
{ 
    if (!initialized) 
    { 
     threadExecutor = Executors.newScheduledThreadPool(1); 
     // start the thread that will perform a scheduled check for unsaved player state 
     threadExecutor.scheduleAtFixedRate(new Runnable() { 
      @Override public void run() { 
       // ... the saving operation ... 
      } 
     }, 0, 120, TimeUnit.SECONDS); 

     initialized = true; 
    } 
} 

當我在調試模式是,這個事情的作品既當應用程序在前臺和後臺太,如預期的那樣。 當我切換到RELEASE模式時出現問題:一旦應用程序在後臺(例如按主頁按鈕),此線程停止並且操作不再重複!

是否有關於此(意外?)行爲的任何文檔?

+1

http://stackoverflow.com/questions/14606039/after-i-press-home-button-scheduledexecutorservice-does-not-run-in-the-backgroun建議使用報警管理器 – user3487063 2014-09-05 13:10:24

+0

好的,有沒有什麼缺點如果我設置鬧鐘以這麼短的時間速率(2分鐘)進行操作? – TheUnexpected 2014-09-05 13:22:54

+1

我想應該沒有缺點。以下是每2分鐘運行一次的鬧鐘管理器示例:http://androidexample.com/Create_Repeating_Alarm_Start_After_Each_2_Minutes/index.php?view=article_discription&aid=93&aaid=116 – user3487063 2014-09-05 13:30:14

回答

0

嘗試使用AlarmManager,每'x'分鐘運行一個任務。

欲瞭解更多信息請參閱this

here是每2分鐘運行一次AlarmManager的示例。

相關問題