2014-09-05 22 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的示例。

相关问题