持续运行的后台服务 [英] Continually Running Background Service

查看:29
本文介绍了持续运行的后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是 sdk 版本 27,最低版本为 19,并试图获得在后台连续运行的服务.我尝试了不同的服务启动选项,但它仍然被应用程序杀死.我尝试使用 BroadcastReceiver 在它被杀死时启动服务,但这给了我一个错误,说该应用程序在后台并且无法启动服务,所以我尝试使用 JobScheduler 并且给了我同样的错误.这应该怎么做?例如,如果我正在制作计步器应用程序,我如何让它在后台运行?

I'm targeting sdk version 27 with a minimum version of 19 and trying to get a service that runs continuously in the background. I tried different service start options but it still got killed with the app. I tried using a BroadcastReceiver to start the service when it got killed but that gave me an error saying that the app was in the background and couldn't start a service so I tried using the JobScheduler and that gave me the same error. How is this supposed to be done? For example, if I were making a pedometer app, how could I keep that running in the background?

推荐答案

在 oreo 版本中定义了 Android 对后台服务的限制.

In oreo release Android defined limits to background services.

为了改善用户体验,Android 8.0(API 级别 26)强加了应用在后台运行时可以执行的操作的限制.

To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.

如果应用需要一直运行它的服务,那么我们可以创建前台服务.

Still if app need to run its service always, then we can create foreground service.

后台服务限制:当应用处于空闲状态时,存在一些限制对其使用后台服务.这不适用于前台服务,更容易被用户注意到.

Background Service Limitations: While an app is idle, there are limits to its use of background services. This does not apply to foreground services, which are more noticeable to the user.

所以创建一个前台服务.当您的服务运行时,您将在其中放置用户通知.看这个答案(还有很多其他的)

So create a foreground service. In which you will put a notification for user while your service is running. See this answer (There are many others)

现在如果您不希望收到服务通知怎么办.一个解决方案就是.

Now what if you don't want a notification for your service. A solution is for that.

您可以创建一些周期性任务来启动您的服务,服务将完成其工作并自行停止.这样,您的应用就不会被视为耗电.

You can create some periodic task that will start your service, service will do its work and stops itself. By this your app will not be considered battery draining.

您可以使用报警管理器创建周期性任务,作业调度程序Evernote-Jobs工作经理.

You can create periodic task with Alarm Manager, Job Scheduler, Evernote-Jobs or Work Manager.

我使用 Work-Manager 创建了永久运行服务,它运行良好.

这篇关于持续运行的后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆