持续运行的后台服务

编程入门 行业动态 更新时间:2024-10-26 22:29:27
本文介绍了持续运行的后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的目标是 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.

  • 而不是告诉专业人士 &各有优劣.我只是告诉你最好的.工作经理是周期性任务的最佳解决方案.这是通过 Android 架构组件 引入的.
  • 与 Job-Scheduler(仅 >21 API)不同,它适用于所有版本.
  • 它也在 Doze-Standby 模式后开始工作.
  • 制作 Android 启动接收器用于在设备启动后安排服务.

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

更多推荐

持续运行的后台服务

本文发布于:2023-11-27 05:03:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636712.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!