1

I'm experiencing a strange behavior on my Android app. I want to schedule a fixed-rate operation that saves the properties of a "player" object. During the application flow, the user may change it's settings but the saving is performed every 2 minutes by this little task.

The task is run by a static ScheduledExecutorService, initialized when the app starts:

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;
    }
}

When I'm in debug mode, this thing works both when the app is in the foreground and in the background too, as espected. Problems come when I switch to RELEASE mode: once the app is in the background (by pressing the home button, for example), this thread stops and the operation is not repeated anymore!

Is there any documentation about this (unexpected?) behavior?

TheUnexpected
  • 3,077
  • 6
  • 32
  • 62
  • 1
    http://stackoverflow.com/questions/14606039/after-i-press-home-button-scheduledexecutorservice-does-not-run-in-the-backgroun suggests to use alarm manager – user3487063 Sep 05 '14 at 13:10
  • ok, is there any drawbacks if I set the Alarm to operate in a such short amount of time rate (2 minutes)? – TheUnexpected Sep 05 '14 at 13:22
  • 1
    I guess there should be no drawbacks. Here is an example of alarm manager that runs every 2 minutes: http://androidexample.com/Create_Repeating_Alarm_Start_After_Each_2_Minutes/index.php?view=article_discription&aid=93&aaid=116 – user3487063 Sep 05 '14 at 13:30
  • ok thanks! this should be an answer, not a comment ;) – TheUnexpected Sep 05 '14 at 13:30
  • and here is one which runs every minute :http://stackoverflow.com/questions/8999103/isuues-alarm-manager-in-every-1-min-android – user3487063 Sep 05 '14 at 13:31
  • sure I'll post it as an answer. – user3487063 Sep 05 '14 at 13:31

1 Answers1

0

Try using AlarmManager, to run a task every 'x' minutes.

Please refer to this for more information.

And here is an example of an AlarmManager that runs every 2 minutes.

Community
  • 1
  • 1
user3487063
  • 3,672
  • 1
  • 17
  • 24