views:

27

answers:

1

Hi,

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.

+1  A: 

I think what you're looking for is an AlarmManager. See, for example, this question: http://stackoverflow.com/questions/1082437/android-alarmmanager

Ron Romero
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