Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Sending/Receiving a Broadcast Message

Published? true
FormatLanguage: WikiFormat

Problem:

You want to make an activity which receives a simple broadcast messages sent by another activity

Solution:

  1. Setup a broadcast receiver
  • Instantiate message receiver object
  • Create IntentFilter
  • Register your receiver with an activity which must receive broadcast message

Discussion:

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 the Activity

myActivity.registerReceiver(mReceiver, filter);

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">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

2. Publish broadcast event

Intent intent = new Intent(
MyBroadcastMessageReceiver.class.getName());
intent.putExtra("some additional data", choice);
someActivity.sendBroadcast(intent);

See Also:

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.