I am having issues passing a value from an Activity to an already running service. I was wondering what the best approach to take would be? Adding extras wont work as I believe this has to be done before the intent is started? (correct me if i'm wrong).
Any help would be great! I can elaborate if needed.
Dan.
You can send data to a running Service by calling startService() with an Intent . In the Service , onStartCommand() will be called on your running service. This is certainly the easiest method, although there are plenty of others.
Explanation. Using putExtra() method, we can send the data. While using it, we need to call setResult() method in services. We can also store data in a common database and access it on services as well as in Activity.
Primitive Data Types To share primitive data between Activities/Services in an application, use Intent. putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism. The android.
putExtra() method is used for sending the data, data in key-value pair key is variable name and value can be Int, String, Float, etc.
If your service is not an IntentService
, you can call startService(...)
as many times you want. The service will run the first time but next calls will result in new onStartCommand()
calls with the new extras you need.
Check this answer and the doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With