Android“错过”了使用 ScheduledExecutorService 定期执行线程
我有一个Android应用程序,它反复从周围的wifi网络收集指纹(出于科学原因,不侵犯任何人的隐私)。
不管怎样,假设我有一个函数可以完成这项工作,它的名字是 scanWifi()。我最初想这样开始它:
ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
scanWifi();
}
}, 0, interval, TimeUnit.MILLISECONDS);
遗憾的是,这只有在手机插入时才能可靠地工作。如果它拔出并放置一段时间,它不会每分钟运行我的 scanWifi() 函数。有时,对 scanWifi() 的单次调用之间会有几分钟的间隔。
我还尝试使用 Timer/TimerTask 做同样的事情,但结果也很差。
到目前为止,唯一看起来或多或少可靠的方法是将其发布到处理程序并重复调用它,如下所示:
Handler h = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
if (!mIsStopped) {
scanWifi();
h.postDelayed(this, mInterval);
}
}
};
h.post(r);
为什么会这样? CPU 是否处于睡眠状态,从而错过了预定的执行?我在我的应用程序中持有部分唤醒锁。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在寻找的是 AlarmManager。例如,请参阅以下问题:Android:如何使用 AlarmManager
I think what you're looking for is an AlarmManager. See, for example, this question: Android: How to use AlarmManager