Chris Knight
Chris Knight

Reputation: 25064

If a Service is stopped, what happens to background threads?

If I have an Android Service which, in onStartCommand, has the following:

MyWidgetUpdater updater = new MyWidgetUpdater();
updater.updateWidgets(...);

The updater retrieves data in a background thread and then updates the widget(s) on the foreground thread. What happens if the service is stopped (e.g. stopSelf()) before the background processing is complete? Will this cause the widgets to sometimes not complete their update (as the thread is presumably killed)? If so, is there a design pattern to know when all of your widgets have completed updating and its safe to stop the service?

Upvotes: 1

Views: 453

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006604

What happens if the service is stopped (e.g. stopSelf()) before the background processing is complete?

Assuming that this is a thread you forked yourself, Android is oblivious to that thread, which will keep running, leaked, until Android terminates your process.

If so, is there a design pattern to know when all of your widgets have completed updating and its safe to stop the service?

Don't call stopSelf() until the work is completed. I do not know where you are calling stopSelf(), but in the pattern you are citing, it would typically be done at the end of that thread.

This is one reason why IntentService is popular: it handles all the thread and stopSelf() stuff for you.

Upvotes: 3

Related Questions