不知何故,我很难解析 START_STICKY
标志的official description:
从onStartCommand(Intent,int,int)返回的常量:如果此服务的进程在启动时被终止(从onStartCommand(Intent,int,int)返回后),则将其保留在启动状态但不保留这意味着什么 . 稍后系统将尝试重新创建服务 . 因为它处于启动状态,所以它将保证在创建新服务实例后调用onStartCommand(Intent,int,int);如果没有任何挂起的启动命令要传递给服务,它将使用null intent对象调用,因此您必须注意检查这一点 . 此模式适用于将显式启动和停止运行任意时间段的事物,例如执行背景音乐播放的服务 .
具体来说,以下四个部分没有技术意义(也就是让我去WTF):
-
"if this service's process is killed ..., then leave it in the started state" [你怎么留下在开始状态下被杀的东西?]
-
"Later the system will try to re-create the service. Because it is in the started state, ..." [如果系统尝试重新创建服务,为什么它处于启动状态?]
-
"Because it is in the started state, it will guarantee to call onStartCommand(...) ..." ["it will guarantee to call"?对不起,不能用语言解析那个短语]
-
"This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, ..." ["and stopped to run" ??]
有没有人对这面旗帜有更好的规范?并且,对于任何阅读此内容的Google员工:wtf?你能在内部修复吗?
2 回答
如您所知,Android中有两种服务形式:
Started service
Bound service
理解描述的关键是
Started service
必须管理自己的生命周期,即只能通过调用stopService()
来调用stopSelf()
或其他组件来停止服务的唯一组件是服务本身 . 一旦启动Started service
(onStartCommand()
返回),它就处于启动状态,除非调用stopSelf()
或stopService()
,否则它不会停止 . 因此,如果系统过早地终止服务(既没有调用stopSelf()
或stopService()
),则服务仍然被认为处于启动状态 . 并且由你在onStartCommand()
中返回一个标志来杀死它之后,告诉(发信号通知)系统如何继续服务 .可能对Extending the Service class末尾给出的
START_STICKY
标志的描述会更清楚 .附:关于"and stopped to run??"混淆,请尝试将其视为"...explicitly started and stopped in order to run..."
EDIT:
另外看看this question .
START_STICKY and START_NOT_STICKY