2012-02-13 125 views
6

有没有一种方法可以防止ActivityManager在“崩溃”后自动重新启动服务?在某些情况下,我强制终止程序退出服务,但不希望Android继续重新启动它。Android:如何防止服务在崩溃后重新启动?

+1

显示您的骨架服务实现。 – 2012-02-13 19:06:25

+0

它是一个常规服务还是一个IntentService? – 2012-02-13 19:11:02

回答

1

您的服务可以将值存储在SharedPreferences中。例如,您可以在每次启动服务时存储这样的内容: store(“serviceStarted”,1); (“serviceStarted”,0);

当您的服务正式终止(您发送消息时这样做),您覆盖此值: store(“serviceStarted”,0);

当您的服务下次重新启动时,它会检测到serviceStarted值为“1” - 这意味着您的服务没有正常停止,并且它自己重新启动。当你发现这个时,你的服务可以调用:stopSelf();取消自己。

欲了解更多信息: http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle

30

这种行为是由onStartCommand()返回值在Service实现定义。常量START_NOT_STICKY告诉Android如果在进程“终止”时运行,则不要重新启动该服务。换句话说:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // We don't want this service to continue running if it is explicitly 
    // stopped, so return not sticky. 
    return START_NOT_STICKY; 
} 

HTH

+3

虽然没有标记为可接受的解决方案,但这是正确的答案 – scooterman 2012-06-06 21:59:30

+0

如果有突出的意图,它将无法正常工作。我有这个问题,上述方法不起作用。下面的方法可能是更好的选择,但我还没有实现它。已尝试其他方法建议堆栈溢出,但它们尚未成功。 – 2014-03-23 15:26:48

+0

@BrianReinhold你的问题听起来像它在这个问题上有一个特定的转折,你有没有发布你自己的解释你的用例和你观察到的问题?我有兴趣多看看它。 – Devunwired 2014-03-23 20:52:34

5

这是我的情况下想出了解决方案它可以帮助别人。即使使用START_NOT_STICKY,我的应用程序仍然会重新启动。因此,我检查是否意图是null这意味着系统重新启动服务。

@Override 
public int onStartCommand(@Nullable Intent intent, int flags, int startId) { 
    // Ideally, this method would simply return START_NOT_STICKY and the service wouldn't be 
    // restarted automatically. Unfortunately, this seems to not be the case as the log is filled 
    // with messages from BluetoothCommunicator and MainService after a crash when this method 
    // returns START_NOT_STICKY. The following does seem to work. 
    Log.v(LOG_TAG, "onStartCommand()"); 
    if (intent == null) { 
     Log.w(LOG_TAG, "Service was stopped and automatically restarted by the system. Stopping self now."); 
     stopSelf(); 
    } 
    return START_STICKY; 
} 
+0

)谢谢!我有要求频繁的位置更新,并将其从服务发送到服务器。通知为基础的前台服务,但是当应用程序关闭时,它停止接收位置更新。经过2天的努力,我达到了你的答案并调整了你的代码。'stopSelf()'之前,我配置了'AlarmManager'现在延迟10秒。而且,这项工作非常顺利,现在不断从服务中获取位置更新。非常感谢! – manoj 2017-11-13 18:52:06

相关问题