当应用程序处于后台(并处于“发布”模式)时,scheduleAtFixedRate()不起作用

时间:2014-09-05 13:00:43

标签: java android scheduled-tasks

我在Android应用上遇到了一种奇怪的行为。 我想安排固定费率操作,以保存"播放器"宾语。在应用程序流程中,用户可以更改其设置,但是通过这个小任务每2分钟执行一次保存。

任务由静态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 个答案:

答案 0 :(得分:0)

尝试使用AlarmManager,每隔'x'分钟运行一次任务。

有关详细信息,请参阅this

here是每2分钟运行一次的AlarmManager示例。