在 Android 中安排保证在接近预定时间运行的任务的最佳方法是什么?

发布于 2024-12-26 05:23:06 字数 733 浏览 3 评论 0原文

我一直在使用计时器和带伪代码的 TimerTask:-

 samplingTask = new TimerTask() {

   public void run() {
     collectSample();
   }

 };

 timer.schedule(samplingTask, 60*1000, 60*1000); //1 min

该应用程序是一个长时间运行的应用程序(例如,在没有唤醒锁的情况下运行 15 分钟,并且屏幕关闭)。安排此任务后,我锁定屏幕并且手机处于运动状态(为加速计激活传感器管理器)。因此,理想情况下,该任务应该每分钟运行一次。然而,在日志中,我看到预定的计时器仅在第 5 分钟、第 9 分钟和第 12 分钟运行。

FINER: (13,Timer-0,Workout)In Timertask, nth minute=5
FINER: (13,Timer-0,Workout)In Timertask, nth minute=9
FINER: (13,Timer-0,Workout)In Timertask, nth minute=12

我的要求是时间关键型采样,可接受的延迟范围为几秒(1-5 秒)。看来,如果设备处于睡眠模式,计时器不会唤醒它并运行计划任务。有没有其他替代方案。文档说可以使用 AlarmManager 和 Handler 。我认为 AlarmManager 理想情况下应该用于执行基于某些系统警报的单次任务。我是否缺少某些东西或实现此功能的替代方案。

I have been using Timer & TimerTask with Pseudocode:-

 samplingTask = new TimerTask() {

   public void run() {
     collectSample();
   }

 };

 timer.schedule(samplingTask, 60*1000, 60*1000); //1 min

This application is a long running app (e.g. say 15 minutes without wakelock, and the screen turned off). After scheduling this task, I lock the screen and the phone is in motion (with sensor manager activated for accelerometer). So, ideally this task should run every minute. However, in the logs, I see that the scheduled timer was run at 5th minute, 9th minute and 12th minute only.

FINER: (13,Timer-0,Workout)In Timertask, nth minute=5
FINER: (13,Timer-0,Workout)In Timertask, nth minute=9
FINER: (13,Timer-0,Workout)In Timertask, nth minute=12

My requirement has time-critical sampling with an acceptable delay range of few seconds (1-5 seconds).It appears that if the device is in sleep mode, timer doesn't wake it up and run the scheduled task. Is there any other alternative to this. Documentation says AlarmManager and Handler can be used. I think AlarmManager should ideally be used to do a single shot task based on some system alarm. Is there something I am missing or some alternative to achieve this functionality.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

套路撩心 2025-01-02 05:23:06

您可以使用AlarmManager - 它有机会削弱设备并重复运行某些任务。

我不太清楚,但假设,当用户关闭屏幕时,所有任务都会暂停,并且在设备睡眠时无法执行任何代码。

You can use AlarmManager - it has opportunity to weak up device and run some task repeatedly.

I don't know exactly, but suppose, when user switches off the screen all tasks paused and can't do any code, while device sleep.

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