1

I have an android app that repeatedly collects fingerprints from the wifi-networks that are around (for scientific reasons, not to invade anybodies privacy).

Anyways, imagine I have a function that does this work and it's called scanWifi(). I initally wanted to start it like this:

ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();

mExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        scanWifi();
    }
}, 0, interval, TimeUnit.MILLISECONDS);

Sadly, this only works reliably when the phone is plugged in. If it's plugged out and lays there for a while, it doesn't run my scanWifi() function every minute. Sometimes there are gaps of several minutes between single calls to scanWifi().

I also tried doing the same thing using a Timer/TimerTask with similarly poor results.

The only thing that seems to work more or less reliable until now is to post it to a handler and call it repeatedly, like this:

Handler h = new Handler();
Runnable r = new Runnable() {
    @Override
    public void run() {
        if (!mIsStopped) {
            scanWifi();
            h.postDelayed(this, mInterval);
        }
    }
};
h.post(r);

Why is that the case? Is the CPU sleeping and thus misses the scheduled execution? I hold a partial wakelock in my app.

pableu
  • 3,200
  • 4
  • 23
  • 21

1 Answers1

2

I think what you're looking for is an AlarmManager. See, for example, this question: Android: How to use AlarmManager

Community
  • 1
  • 1
Ron Romero
  • 9,211
  • 8
  • 43
  • 64
  • Sorry that it took so long to accept your answer. I have completely forgotten about this, I think my problem was that I did *not* hold a partial wakelock, although I thought I did. Anyways, I have now acquired a partial wakelock and my ExecutorService works as it should :-) – pableu Oct 14 '10 at 13:13
  • 1
    For anyone looking to use this implementation it should be noted, that starting from Android 5.1 AlarmManager no longer accepts recurring alarms with intervals shorter than 60 seconds. Anything less than that defaults to a minute. https://code.google.com/p/android/issues/detail?id=161244 – Janne Oksanen Sep 21 '15 at 09:11