0

Say I have an Activity that launches a Service using startService() when user presses a button. The service is stopped using another intent in startService() when user presses another button, or it can decide to stop itself. The service wants to run forever, so it returns START_STICKY from onStartCommand(). While the service is running, it connects to some server and receives messages. Activity binds to it and, when bound, displays those messages.

Now, when the Activity is started after an OOM kill, it doesn't know if the Service is started. One can use a static field set in onStartCommand() to tell if the Service is running, but that's prone to backfire sooner or later. Moreover, the Service can be started by the system after the activity has been launched, so using a static field is not an option at all.

The cleanest solution I can come up with is using SharedPreferences to store the state of the service. This is going to fail to be good when the service is killed between SharedPreferences.setBoolean("running", false) and stopSelf(), but such a thing will probably occur rarely.

Also I can try to bind to the Service at all times. This would be very ugly but still not impossible.

Any other solutions? Maybe the very idea is wrong in some way?

squirrel
  • 5,114
  • 4
  • 31
  • 43
  • "the Service can be started by the system after the activity has been launched, so using a static field is not an option at all" -- I don't see why not. Set a `static boolean` in `onCreate()` of the service. – CommonsWare Oct 14 '15 at 23:59
  • If the Service started before the Activity, I can check if a static boolean is set in `Activity.onCreate()` or sth. But if the Service hasn't yet started, that boolean would be `false`. – squirrel Oct 15 '15 at 00:04
  • Couple the `boolean` with an event bus message. Or, use Otto's `@Producer` or greenrobot's EventBus' sticky events to handle the components (activity and service) starting in either order. – CommonsWare Oct 15 '15 at 00:07
  • @CommonsWare thanks for the suggestion, EventBus is a mighty helpful thing, moved a lot of logic into it. Doesn't really solve the problem: if the service is not going to be run, you won't get any event. I ended up using a boolean in the preferences and launching the service when the activity starts—just in case the system was not going to launch it – squirrel Oct 24 '15 at 18:16

0 Answers0