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模式时出现问题:一旦应用程序在后台(例如按主页按钮),此线程停止并且操作不再重复!
是否有关于此(意外?)行为的任何文档?
http://stackoverflow.com/questions/14606039/after-i-press-home-button-scheduledexecutorservice-does-not-run-in-the-backgroun建议使用报警管理器 – user3487063 2014-09-05 13:10:24
好的,有没有什么缺点如果我设置闹钟以这么短的时间速率(2分钟)进行操作? – TheUnexpected 2014-09-05 13:22:54
我想应该没有缺点。以下是每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