Sending/Receiving a Broadcast Message
You want to make an activity which receives a simple broadcast messages sent by another activity
- Setup a broadcast receiver
- Instantiate message receiver object
- Create IntentFilter
- Register your receiver with an activity which must receive broadcast message
1. Setup broadcast receiver
Create the receiver class by extending android.content.BroadcastReceiver.
The method onReceive() of this class will be called when broadcast is sent.
You can either instantiate the receiver in your activity code, or declare it in XML.
In the case of manual creation, which may be an inner class to your Activity,
you need to instantiate it and register it, along with creating an IntentFilter object.
MyBroadcastMessageReceiver mReceiver = new MyBroadcastMessageReceiver();
Create an IntentFilter.
IntentFilter filter = new IntentFilter(MyBroadcastMessageReceiver.class.getName());
Again in this case, you need to register your Receiver with your activity which is to receive broadcast messages.
Now whenever this type of message is generated somewhere in the system, the
mReceiver.onReceive() method will be called within thr main thread of
OTOH, if you are using XML, you declare the Receiver in your AndroidManifest, and provide its intent filter there too. For example, a BroadcastReceiver that tracks the state of the network connection could be registered as follows:
<receiver android:name=".net.NetworkStateListener" android:exported="false">
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
2. Publish broadcast event
Intent intent = new Intent(
intent.putExtra("some additional data", choice);
If your sender and receiver are always going to be in the same app, it is more efficient, and simpler form a security point of view, to use the LocalBroadcastManager to register and send; see 4547.