Android: How to prevent service restart after crash?

Is there a way to prevent my ActivityManager service from automatically restarting after it crashes? In some scenarios, I forcefully kill my service when I exit the program, but I do not want Android to continue to restart it.

+6
source share
3 answers

This behavior is determined by the return value of onStartCommand() in your Service implementation. The START_NOT_STICKY tells Android not to restart the service if it is 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; } 

NTN

+30
source

Here is the solution I came up with if this can help someone else. My application is still restarting even with START_NOT_STICKY . So, instead, I check if null makes sense, which means the service has been 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; } 
+5
source

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

When your service is interrupted (you send a message for this), you override this value: store ("serviceStarted", 0);

The next time the service reboots, it will find that the value of serviceStarted is "1" - this means that your service has not been stopped and it has restarted itself. When you find this, your service may call: stopSelf (); to cancel yourself.

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

+1
source

Source: https://habr.com/ru/post/908362/


All Articles