Communicate with Activity from Service (LocalService) - Android Best Practices
Solution 1
I think the best design would be the Android LocalService example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
I wouldn't. Use the loosest possible coupling you can stand. Hence, on average, aim for the command pattern with startService()
instead of the binding pattern with bindService()
. Notably, binding is a bit of a pain when it comes to dealing with configuration changes (e.g., screen rotations).
What is the best way for the Service to call the Activity? Do I use Intents, BroadcastReceivers, Messages? How?
See Notify activity from service
Solution 2
If you need tight coupling between your activity using bindService(), the way you communicate depends on who is originating the communication.
If the Service is originating (due to say an Alarm that has some new information to share), it would typically send a broadcast.
If the Activity is originating (due to say your example "go fetch something from server"), it could be handled asynchronously using AsyncTask or similar. That is, you could fetch from the server in the AsyncTask.doInBackground(), and post the results back to the activity in AsyncTask.onPostExecute. This scenario be a bit more complicated if the requested operation is expected to take a very long time - in which case I would de-couple it, and send a broadcast back from the Service instead.
paulpooch
Updated on July 29, 2020Comments
-
paulpooch over 3 years
Common scenario - Activity with a background Service to poll server.
The Service will run periodically via AlarmManager and also perform tasks for the Activity (user hits a button, go fetch something from server).
I'd like to know the best practices here. I think the best design would be the Android LocalService example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
However in the example the Activity has a reference to the activity
mBoundService
but there is no reverse connection (the Service has no way to call the Activity).What is the best way for the Service to call the Activity?
Do I use Intents, BroadcastReceivers, Messages? How?
-
paulpooch about 13 yearsWell I actually based it off your tutorial: github.com/commonsguy/cw-andtutorials/tree/master/… Is there anything bad about this approach?
-
CommonsWare about 13 years@paulpooch: Well, let's just say I'm rewriting all the Patchy tutorials in the next couple of months.
-
Mixaz over 9 yearsI feel I need to provide a link here to another @CommonsWare post where he says that Service binding can have less pain when bound to an Application object instead of Activity stackoverflow.com/a/15235902/1028256 ))