Android:准备好重复性后台任务 Android Oreo 的最佳方法是什么?

Android: What is the best way to make repetitive Background Tasks Android Oreo ready?

我听说后台服务不会在 android Oreo 上免费运行。 我有点困惑我应该如何重写我的代码。 我和 android 一起工作了一个月左右,所以请尝试 尽量简单回答。

我在 MainActivity 的 onCreate() 中有一个名为 On Boot 的服务。 在服务的 onStartCommand 中,它正在调用 Handler。 该处理程序将每半分钟 postDelay() 自身并调用一个函数。 此函数执行一些 api 请求,并在应用某些条件时推送通知。

让此代码在 android O+ 上运行的最佳方法是什么?

我考虑过使用前台服务并显示无用的 ongoing 通知,用户可以 看不见,但这个想法听起来不太好。

This handler will postDelay() itself every half minute and call a function

这在 Android 6.0+ 上无法可靠运行,这要归功于打瞌睡模式和应用待机。特别是在几乎任何地方频繁工作都会对电池不利,因此 Google 将竭尽全力防止这种行为。

What is the best way to let this code work on android O+?

最好的办法是完全摆脱它。使用 JobScheduler 并减少周期性工作的频率(例如,每 15 分钟一次)。

使用前台服务将使您的应用在 Android 8.0+ 上的运行方式与在 Android 6.0+ 上的运行方式相同(即仍然不可靠,但至少工作一分钟以上).

I thought about using a Foreground Service and display a useless ongoing notification, the user can make invisible but that idea does not sound good.

制作有用的通知,允许用户控制服务的行为。

使用 GcmNetworkManager。您可以设置更频繁间隔的周期性任务。由于它使用关于 api 级别的不同结构,您可能不会对奥利奥产生任何问题。