Wednesday, July 11

Android: Broadcast locally within the app

Previously, when I need to pass some info between my Activity and Service classes, I will use Broadcast class to send a new intent containing the info from the service side, then register a receiver at the activity side. However, Broadcast class is mainly used to send info across apps, e.g. you could send some info from your app to the calendar app to create a new calendar event: it is not for communication occurred inside one app. Exposing your in-app info globally might raise security issues and also not efficient.

OK, then I find this LocalBroadcastManager class, which, according to its name, mange the local broadcast, i.e. passing info within the app (from one app component to another). This is perfect for my use. While the official doc does not provide any details on how to use it, here is an excellent tutorial covering everything we need. I summarize below just for reference:

1. get the library
This class belongs to the support package, which means you have to add the package as a 3rd-party lib  and then import android.support.v4.content.LocalBroadcastManager.

2. create the sender
Pretty straightforward.

3. create the receiver
To receive any intents, globally or locally, you first have to create and register your own broadcast receiver:

All done. Very convenient to use.

No comments:

Post a Comment