简体   繁体   中英

Android: How to prevent service from restarting after crashing?

Is there a way to prevent my Service from automatically being restarted by ActivityManager after it "crashes"? In some scenarios, I forcefully kill my service on program exit, but do not want Android to keep restarting it.

This behavior is defined by the return value of onStartCommand() in your Service implementation. The constant START_NOT_STICKY tells Android not to restart the service if it s running while the process is "killed". In other words:

@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

Here's the solution I came up with in case it could help someone else. My app still restarted even with START_NOT_STICKY . So instead i check to see if the intent is null which means the service was restarted by the system.

@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;
}

Your service can store a value in the SharedPreferences. For example you can store something like this everytime your service starts: store("serviceStarted", 1);

When your service terminates regulary (you send a message to do so) you override this value: store("serviceStarted", 0);

When the next time your service restarts itself it detects that the serviceStarted value is "1" - that means that your service wasnt stopped regulary and it restarted itself. When you detect this your service can call: stopSelf(); to cancel itself.

For more information: http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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