Android“错过”了使用 ScheduledExecutorService 定期执行线程

发布于 2024-09-16 13:14:10 字数 1014 浏览 4 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏半生如梦愿梦如真 2024-09-23 13:14:10

我认为您正在寻找的是 AlarmManager。例如,请参阅以下问题:Android:如何使用 AlarmManager

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文