Sending Data to a Running Service
Don't ask me why, but there have been cases where I was working on an Android app, which needed me to send some data to my already running Service. At one point, I even worked on a problem where I had to send data from one running service to another.
After going down the rabbit hole regarding my problem, I decided to write an article on the same. In this article let's discuss how to send data to a running service.
The simplest way to send data to a running service is by starting the service again using the
startService() method. You can add any extras needed to the intent and access it within the service class.
Accordingly, you will then have to override the
onStartCommand() method in your service class and handle the logic of accessing the data appropriately.
- Start a service for the first time using the
- The service's
onStartCommand()methods would be executed.
- When you want to send any additional data, call
startService()again with the new data.
- This time, because the service is already running, just the
onStartCommand()method would be executed.
- You can override this method i.e.
onStartCommand()and access any
extrasthat you may have passed.
This seems like a crude way, doesn't it? To add to that, there are restrictions on creating background services when your app is in the background, which could cause your app to crash. So let's look at a better way to implement this.
Using Intent Filter & Broadcasts
The idea here is to send a broadcast in your app (from an Activity/Fragment/Service), which can be received and parsed by your running Service.
In your Activity/Fragment/Service, all you have to do is create an intent and send the same as a broadcast. In our example, we'll execute this code with the click of a button.
In your running service, create an intent filter, and a broadcast listener for the same. You can register the listener in the
onCreate() method of your Service and deregister the listener in the
onDestroy() method of the Service to avoid any leaks. Sample code shared below.
You can access the data you have passed from the intent using
getStringExtra() or other similar methods. More over here.
I've created a small app to demonstrate this, which you can find over here. Furthermore, in the example you can check your Logcat, each time you sent the broadcast, the broadcast has been received by the service.
So as you can see this is a much cleaner and simpler way of sending data to an already running service. You can use this method even in other use cases in communication from a service to an activity, activity to service, service to service and a lot more.
Thanks for reading, and hope you enjoyed this article. Do comment if you have any questions or suggestions.
Recommended reading -
- Android Developer Docs - Broadcasts
- Stack Overflow - Starting a Service Multiple Times