繁体   English   中英

Android:崩溃后如何防止服务重启?

[英]Android: How to prevent service from restarting after crashing?

有没有办法阻止我的服务在“崩溃”后被ActivityManager自动重启? 在某些情况下,我在程序退出时强行终止我的服务,但不希望Android继续重启它。

此行为由Service实现中onStartCommand()的返回值定义。 常量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

这是我提出的解决方案,以防它可以帮助别人。 即使使用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;
}

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

当您的服务以常规方式终止时(您发送消息),您将覆盖此值:store(“serviceStarted”,0);

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

有关更多信息,请访问: http//developer.android.com/reference/android/app/Service.html#ServiceLifecycle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM