简体   繁体   English

在 Android 上定期安排后台任务

[英]Scheduling a background task periodically on Android

I'm working on an app where I have to read data from multiple sensors and send it to a remote server every 15 minutes.我正在开发一个应用程序,我必须每 15 分钟从多个传感器读取数据并将其发送到远程服务器。 This has to be done when the app is closed/killed as well and I also have to be sure it always executes.这也必须在应用程序关闭/终止时完成,我还必须确保它始终执行。 I also want to be sure it happens (almost) exactly every 15 minutes (+-1 minute difference is the upper limit).我还想确保它(几乎)恰好每 15 分钟发生一次(+-1 分钟的差异是上限)。

At this point, I've found 3 options: using Workmanager, Alarmmanager or using a foreground service.此时,我找到了 3 个选项:使用 Workmanager、Alarmmanager 或使用前台服务。 Following the documentation , Workmanager seems the way to go for background tasks, however, after having done some reading, Alarmmanager seems to be a safer choice (Workmanager sometimes has troubles with doze mode, and the timing isn't exact because it uses a flex period of at least 5 minutes).按照文档,Workmanager 似乎是 go 用于后台任务的方式,但是,在阅读了一些内容之后,Alarmmanager 似乎是一个更安全的选择(Workmanager 有时会遇到打瞌睡模式的问题,并且时间不准确,因为它使用 flex至少5 分钟)。 And a foreground service is not really allowed for this kind of task (it's not really long running, it's just a periodic task) and is being limited in newer Android versions.并且这种任务实际上不允许使用前台服务(它并不是真正长时间运行,它只是一个周期性任务)并且在较新的 Android 版本中受到限制。 Do you think it would be a good idea to use an Alarmmanger for this task, or should I use something else?您认为使用 Alarmmanger 来完成这项任务是个好主意,还是我应该使用其他东西? Thanks!谢谢!

TODO Background scheduling.. You can use this method todo your stuff.. TODO后台调度.. 你可以使用这个方法来做你的事情..

KOTLIN; KOTLIN;

val service = Executors.newSingleThreadScheduledExecutor()
        val handler = Handler(Looper.getMainLooper())
        service.scheduleAtFixedRate({
            handler.run {
                // Do your stuff here, It gets loop every 15 Minutes
            }
        }, 0, 15, TimeUnit.MINUTES);

JAVA; JAVA;

  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        Handler handler = new Handler(Looper.getMainLooper());

        service.scheduleAtFixedRate(() -> {
            handler.post(() -> {
                // Do your stuff here, It gets loop every 15 Minutes
            });
        }, 0, 15, TimeUnit.MINUTES);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM