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

我听说后台服务无法在
Android Oreo上免费使用.

我有点困惑,我应该如何重写我的代码.

我现在正在使用android一个月左右,所以请尽量

回答尽可能简单.

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

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

我考虑使用Foreground Service并显示无用的持续通知,用户可以制作
看不见但这个想法听起来不太好.

最佳答案

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

这在Android 6.0上无法可靠地运行,由Doze模式和应用程序待机提供.特别是在几乎任何地方工作都会对电池造成不利影响,因此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.

发出有用的通知,允许用户控制服务的行为.

点赞