在一个服务中,onStartCommand方法应该返回什么?

20

我一直在查阅文档,有时候onStartCommand() 返回 START_NOT_STICKY,有时候返回以下内容:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
}

我现在很困惑,为什么有些服务会返回 super.onStartCommand(intent, flags, startId);

3个回答

14
一切取决于您想要什么。 文档说:

为了向后兼容, 默认实现调用 onStart(Intent, int) 并返回 START_STICKY 或 START_STICKY_COMPATIBILITY。

因此,返回 super.onStartCommand() 等同于返回 START_STICKY。 如果您不想使用默认行为,则可以返回其他常量。

3
谢谢您的回答。我有一个问题。如果我没有在我的服务中重写onStartCommand()方法,那么默认会返回什么值?系统将如何对待我的服务以进行重新启动/停止? - Kushal
1
我认为它会返回 START_STICKY - CopsOnRoad

4

最常用的有:

  • Service.START_STICKY
  • Service.START_NOT_STICKY
  • Service.START_REDELIVER_INTENT

Service.START_STICKY会在Android系统由于任何原因终止后重新启动。 Service.START_NOT_STICKY会一直运行,直到它有待处理的任务。 Service.START_REDELIVER_INTENT类似于Service.START_STICKY,但原始Intent将被重新传递给onStartCommand方法。


0
 Service.START_STICKY
>> the system restarts the service with everything refresh not using the previous intent. 
Service.START_NOT_STICKY 
>> the system does not restarts the service.
Service.START_REDELIVER_INTENT
>>the system restarts the service with using the previous intent.`enter code here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接