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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
3. create the receiver
To receive any intents, globally or locally, you first have to create and register your own broadcast receiver:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
}; |
All done. Very convenient to use.
No comments:
Post a Comment