1

I try to develop a simple timer beeper, that peep hourly. For the timing I use a Service and handler, here the example:

    void onStart(...){
        handler.postDelayed(timerRunnable, ONE_HOUR);
    }

    private Runnable timerRunnable = new Runnable() {

    @Override
        public void run() {
               ...beep
               handler.postDelayed(timerRunnable, ONE_HOUR);
        }
    };

but run() method will be fired nondeterministic, I think it is dependent from the current device usage.

I have try the same scenario with TimerTask and with 'manualy' Thread implementation, but with the same nondeterministic result.

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
Mark
  • 17,887
  • 13
  • 66
  • 93

2 Answers2

5

You'll probably have better luck using the AlarmManager for such a long delay. Handler is best for ticks and timeouts while your app is in the foreground.

http://developer.android.com/reference/android/app/AlarmManager.html

LeffelMania
  • 12,765
  • 4
  • 32
  • 34
0

Android is not a real-time operating system. All postDelayed() guarantees is that it will be at least the number of milliseconds specified. Beyond that will be dependent primarily on what the main application thread is doing (if you are tying it up, it cannot process the Runnable), and secondarily on what else is going on the device (services run with background priority and therefore get less CPU time than does the foreground).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • with undeterministic I mean up to 20 minutes later :( – Mark Apr 28 '11 at 21:03
  • 1
    @Mark: @LeffelMania speaks truth! You do *not* want to have a service hanging around memory solely to mark time of that duration. Please please please use `AlarmManager` for something like this. It'll fix your problem as a side-effect. – CommonsWare Apr 28 '11 at 21:23