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?
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.
Don’t call
stopSelf()until the work is completed. I do not know where you are callingstopSelf(), but in the pattern you are citing, it would typically be done at the end of that thread.This is one reason why
IntentServiceis popular: it handles all the thread andstopSelf()stuff for you.