在应用程序被销毁后管理服务状态

Manage service state after application being destroyed

我的应用程序有一个场景。这是如下: 我想在后台服务中使用倒数计时器,即使应用程序已从堆栈中删除,它也会在后台使用 运行。因为我想为特定时间间隔生成通知,即使应用程序不在堆栈中。 请给我一些建议如何在应用程序被销毁后管理服务。 提前致谢。

检查AlarmManager

Alarms have these characteristics:

  • They let you fire Intents at set times and/or intervals
  • You can use them in conjunction with broadcast receivers to start services and perform other operations.

  • They operate outside of your application, so you can use them to trigger events or actions even when your app is not running, and even if the device itself is asleep.

  • They help you to minimize your app's resource requirements. You can schedule operations without relying on timers or continuously running background services.

可以找到一个工作示例 here

服务是 运行 在后台运行而不与用户直接交互的组件。由于该服务没有用户界面,因此它不受 activity.

的生命周期限制

服务可以有两种形式:

1) Started/Unbound:在这种情况下,应用程序组件通过调用 startService() 来启动服务,并且它将 继续 运行在后台,即使发起它的原始组件被销毁。例如,启动时,服务会继续在后台播放音乐无限期

2) 绑定:Android 组件可以使用 bindservice() 将自己绑定到服务。只要其他应用程序组件绑定到绑定服务,绑定服务就会 运行。一旦解除绑定,服务就会自行销毁。

Service

服务不是线程,因此您必须在服务内部实现线程。