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

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

问题描述

我的目标是最低版本为19的sdk版本27,并试图获得在后台连续运行的服务.我尝试了其他服务启动选项,但仍然被该应用终止.我尝试使用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.

  • Instead of telling pros & cons of each one. I just tell you best. Work manager is best solution for periodic tasks. Which was introduced with Android Architecture Component.
  • Unlike Job-Scheduler(only >21 API) it will work for all versions.
  • Also it starts work after a Doze-Standby mode.
  • Make a Android Boot Receiver for scheduling service after device boot.

我使用Work-Manager创建了永久运行的服务,效果很好.

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

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