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
// create an intent to hold your info
Intent intent = new Intent("location");
// put your info into the intent
intent.putExtra("test", 99);
// use LBM to send the intent
LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(intent);
view raw sender.java hosted with ❤ by GitHub
Pretty straightforward.

3. create the receiver
To receive any intents, globally or locally, you first have to create and register your own broadcast receiver:
// register the receiver you created and
// add a filter to only receive the intent you need
LocalBroadcastManager.getInstance(this).registerReceiver(
myReceiver, new IntentFilter("location"));
// create your own receiver from BroadcastReceiver class
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// get the info from the intent we received
Double test = intent.getDoubleExtra("test", 20);
Toast.makeText(getBaseContext(), test, Toast.LENGTH_SHORT).show();
}
};
view raw receiver.java hosted with ❤ by GitHub

All done. Very convenient to use.

No comments:

Post a Comment