开发者

Android "misses" periodical execution of Thread using ScheduledExecutorService

I have a开发者_如何学Gon 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜