Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate with Activity from Service (LocalService) - Android Best Practices

Tags:

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?

like image 426
paulpooch Avatar asked Feb 05 '11 17:02

paulpooch


1 Answers

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

like image 88
CommonsWare Avatar answered Oct 06 '22 22:10

CommonsWare