I’m an experienced iOS developer but still consider myself a noob regarding Android development. Never mind, I still want to share my latest experiment with the Android SDK: how to run a long operation in the background while still updating the UI regularly?
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
The question then arises: what should we use when a longer background operation is needed?
Searching for an answer to this question on services like StackOverflow ends up being more confusing than helpful. Many questions are asked in this area but no clear answer appears. But depending on the specific aspects of each
question, many keywords appear to help getting our quest further:
Ideally, I wanted to find something similar to the KVO mechanism in iOS.
The main reason why I picked
Services over other solutions is that I wanted to be able to share any kind of objects, not only
Parcelable ones. This constraint eliminated a solution based on a
LocalBroadcastManager as from my understanding, objects that can be passed with the
Extra) have to be
My objectives for this POC were:
Some notes about it went follow.
The pitch for the POC is as silly as can be. The app will generate in the background a new hex-string every 2 seconds. It will have to be displayed in a screen with a new color. Wow! I’m sure this app would be a hit on the Google Play Store!
When you create a
Service, you need to declare it in your app manifest. I made mine private to my app but it’s not required.
The service itself is a subclass of
IntentService (which provides a convenient
onHandleIntent method to override) doing very simple things:
The service just runs continously and wakes up every 2 seconds to update the
RandomSingleton singleton object via the
increment() method: objectives 1 and 2 are achieved.
Here is the full source code.
The service is started via a button in an activity:
We still have objective 3 to achieve. To do so:
RandomSingletona subclass of
dispatchChange(...)at the end of the
And that’s it.
After a frustrating research that had made me more confused than confident about my problem, I found out that the actual implementation was pretty straightforward and easier to implement than I expected.
Nevertheless, I’m still curious of feedbacks you might have about this code and I invite you to get in touch via GitHub or Twitter if you want to engage a discussion about this page (in particular if you know a better way to do a Service to UI communication).
Also, my message in a bottle is still out there: