My android service needs to have a background thread but I believe I can’t use IntentService as the service needs to be running as much as possible and it won’t be being started and stopped.
I wish to send commands from the UI to the service background thread, how best to do this . I can’t do this with a StartService(intent) call as I won’t be starting and stopping the service. The background thread will be performing network io continuously. Other threads may need to send commands to the service’s worker thread too.
Any ideas most welcome
Thanks
The typical way to do this is with a broadcast receiver. The background thread broadcasts a message that either contains the new data or indicates some data has changed. The UI can then choose to receive these notifications. Your UI also needs to be able to reconstruct itself from available state.
You activity has more freedom in calling the background thread in more direct way, since the Activity’s lifetime is not under your control whereas the lifetime of the background thread is. You can transfer data/messages to a thread in a number of ways, as long as you ensure access is properly synchronized.
One way to do work on a background thread is to use a HandlerThread. Using that, you can post runnables to that thread that will each get run serially. In addition to your background work, you could post requests from the UI as well. This may not be ideal for you, but it’s one possibility.