In my projects I am using BroadcastReceiver
s as a callback from a long running thread (eg. notify the activity that a download was finished and send some response d
This is a very interesting question and I ran into the same problem. In my opinion both mechanisms can be used altogether and the right approach to use depends on your use case. Here are some points to be taken into account before deciding.
Using the callback-mechanism has some benefits, but there are also limitations:
PRO
CONTRA
Observer
/ Observable
mechanism.null
before invoking callback functions if the callback may be optional.Some points regarding the BroadcastReceiver
-approach:
PRO
onReceive()
method is always executed on the main thread.CONTRA
Intent
is an additional error source.Intent
's actions unique (e.g. by prepending the package name) if you want to eliminate correlations with other apps, as their original purpose is to do broadcasts between applications.BroadcastReceiver
-registration and unregistration. If you want to do this in a more comfortable way, you can implement a custom annotation to annotate your Activity with the actions that should be registered and implement a base Activity
class that does registration and unregistration with IntentFilter
s in its onResume()
resp. onPause()
methods.Intent
has to implement the Parcelable
interface, but furthermore there is a strict size limitation and it will cause performance issues if you transport a large amount of data with your Intent
. See http://code.google.com/p/android/issues/detail?id=5878 for a discussion on that. So if you want to send images for example you have to store them temporary in a repository and send a corresponding ID or URL to access the image from the receiver of your Intent
that deletes it from the repository after usage. This leads to further problems if there are several receivers (when should the image be removed from the repository and who should do that?).Intent
s to understand what has triggered a specific error or why this notification chain is broken at some point.In my opinion, even a mobile app should have an architecture base on at least 2 layers: the UI-layer and the core layer (with business logic, etc.). In general, long running tasks are executed in an own thread (maybe via AsyncTask
or HandlerThread
if using MessageQueue
s) inside the core layer and the UI should be updated once this task has been finished. In general with callbacks you achieve a tight coupling between your components, so I would prefer using this approach only within a layer and not for communication across layer boundaries. For message broadcasting between UI- and core-layer I would use the BroadcastReceiver
-approach that lets you decouple your UI layer from the logic layer.