android - Android 服务的 START_STICKY 标志的精确语义

标签 android android-service

不知何故,我很难解析 official description START_STICKY 标志:

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

具体来说,以下四个部分没有技术意义(也就是让我去 WTF):

  • “如果此服务的进程被终止...,则将其保留在启动状态” [如何将已终止的进程保留在启动状态?]
  • “稍后系统会尝试重新创建服务。因为它处于启动状态,...” -创建服务?]
  • “因为它处于启动状态,它会保证调用 onStartCommand(...) ...” [“它会保证调用”?抱歉,无法从语言上解析该短语]
  • “对于将明确启动和停止运行任意时间段的事物,此模式很有意义,...” [“并停止运行” ??]

有人对此标志有更好的说明吗?并且,对于阅读本文的所有 Google 员工:wtf?你能在内部迅速修复它吗?

最佳答案

如您所知,Android 中的服务有两种形式:

理解描述的关键是Started 服务 必须管理自己的生命周期,即只有 可以停止服务的组件通过调用 stopSelf() 或通过调用 stopService() 的另一个组件,service 是服务本身。一旦 Started service 启动(onStartCommand() 返回),它就处于启动状态并且不会除非 stopSelf()stopService() 被调用,否则不会停止。因此,如果系统过早地终止服务(stopSelf()stopService() 都未被调用) ,该服务仍被视为处于启动状态。您可以通过在 onStartCommand() 中返回一个标志来告诉(信号)系统如何在终止服务后继续处理该服务。

可能是Extending the Service class末尾给出的START_STICKY标志的描述你会更清楚。

附言关于“并停止运行??” 混淆,请尝试将其理解为“...明确启动和停止以运行...”

编辑:

另请查看 this question .

关于android - Android 服务的 START_STICKY 标志的精确语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080585/

相关文章:

android - 从方向更改恢复时,DialogFragment onCreateDialog() 在 onServiceConnected() 之前被调用

java - 如何从 2 个不同的数组列表中对数组列表进行排序?就像两个数组列表,性别和学生。如何按性别查看学生详细信息

java - Jackson 解析 JSON(700 KB 文件)需要 30 秒以上

android - Google IO Rest 设计模式,完成 ContentProvider 并坚持从网络获取数据

安卓背景音乐服务

java - 如何使用 FCM 管理聊天应用程序的推送通知

java - 当屏幕关闭时,Android 服务似乎会暂停

java - 如何为线程设置名称?

android - 如何从存储在 Assets 中的本地文件夹添加抖动图像

java - 为什么要创建一个单例 Java 类的两个实例?