How to update UI from background service
I spent a lot of time recently interviewing perspective candidates for an Android developer post and when asked on how to update an activity from a background service, a lot of people did not get it right. So I thought I would post a short article on some of the basic implementations of updating UI from background service.
There are a lot of ways to do that but these are the 3 of the basic implementations and I personally feel that every android developer should be aware of it.
Using LocalBroadcastReceivers
From the official documentation, we know that LocalBroadcastReceivers are a:
Helper to register for and send broadcasts of Intents to local objects within your process.
This is efficient for a couple of reasons:
- You know that the data you are broadcasting won’t leave your app, so don’t need to worry about leaking private data.
- It is not possible for other applications to send these broadcasts to your app, so you don’t need to worry about having security holes they can exploit.
This would be a perfect solution when we want to, for instance,
- Sms Parsing: When sms is received, we would like to parse the incoming sms and update the ui, if an otp from our app is received.
- Notification: When notification is received, we would like to display the notification in the activity
Now let’s see how to implement the first scenario: Sms parsing
Create a custom BroadcastReceiver for parsing the sms.
Register a LocalBroadcastReceiver in the activity class.
And that’s it!
Using ResultReceiver
From the official documentation:
Generic interface for receiving a callback result from someone.
This is very similar to what we have implemented in LocalBroadcastReceiver. For instance, let’s say we would like to create a background service to download an image from a url in the background and display in the activity. First off, we create a custom ResultReceiver class:
Next, we create an intent service.
And finally, let’s set up our activity.
That’s it!
Using Handlers
From the official documentation:
A Handler allows you to send and process
Message
and Runnable objects associated with a thread'sMessageQueue
. Each Handler instance is associated with a single thread and that thread's message queue.
Again, I am taking the same example as above to implement a Handler. So we would like to create a background service to download an image from a url in the background and display in the activity.
First off, we create a custom Handler class:
Next, we create an intent service.
And finally, let’s set up our activity.
And that’s it!
I hope this was helpful. If you thought this was a good article, please don’t forget to clap. Thanks for reading.
Happy coding!