有没有办法阻止我的服务在“崩溃”后被ActivityManager自动重启?在某些情况下,我在程序退出时强行终止我的服务,但不希望Android继续重新启动它。
答案 0 :(得分:31)
此行为由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
答案 1 :(得分: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;
}
答案 2 :(得分:1)
您的服务可以在SharedPreferences中存储值。例如,您可以在每次服务启动时存储类似的内容: store(“serviceStarted”,1);
当您的服务以常规方式终止时(您发送一条消息来执行此操作),您将覆盖此值: store(“serviceStarted”,0);
当您的服务下次重新启动时,它会检测到serviceStarted值为“1” - 这意味着您的服务没有定期停止并且自行重新启动。当你发现这个时你的服务可以调用:stopSelf();取消自己。
了解更多信息: http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle