Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android Apps
GitHub logo Twitter logo OReilly Book Cover Art
Using LocalBroadcastManager to Broadcast and Receive within your applicationBack to Android Cookbook Home | Up to Chapter: Inter/Intra-Application Communication

Author: Ian Darwin ('idarwin')
In Published Edition? Yes
FormatLanguage: WikiFormat

Using LocalBroadcastManager to Broadcast and Receive within your application


You want to use the Broadcast send/receive mechanism, but don't want other apps to see your broadcasts.


Use the LocalBroadcastManager to register your receiver and to send your broadcast Intents.


There are both efficiency and security issues with using the normal BroadcastReceiver mechanism described in 934 to send broadcasts that are actually only meant for use within your application. Why bother everybody else if they shouldn't care? And, what about those who might bother but shouldn't? Using the LocalBroadcastManager to register your receiver and to send your broadcast Intents eliminates both problems.

This thus makes a viable replacement for use of custom Javabean-style event notifiers.

To use it, the receiver must be registered using

LocalBroadcastManager.getInstance(aContext).registerReceiver(handler, receiveFilter);

Then, the sending code has merely to call


In both cases the Context can be an Activity or Service.

To keep the complete example simple, the sending code and the receiving code are in the same Activity; this is not the normal state of affairs.

Be aware that the BroadcastReceiver runs on the same thread that the intent is Broadcast on; in our example this is the main/GUI thread!

public class MainActivity extends Activity {

	private static final String TAG = "LocalBroadcastDemo";
	private IntentFilter receiveFilter;

	protected void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "MainActivity.onCreate()");

		receiveFilter = new IntentFilter(getClass().getName());
			registerReceiver(handler, receiveFilter);

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; items go in the action bar if present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	private BroadcastReceiver handler = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Log.d(TAG, "BroadcastReceiver() {...}.onReceive()");
				"Message received", Toast.LENGTH_LONG).show();

	 * Create and dispatch an Intent via the LocalBroadcastManager.
	 * Called from a Button with android:onClick="send"
	public void send(View v) {
		Log.d(TAG, "MainActivity.send()");
		Intent sendableIntent = new Intent(getClass().getName());

XXX Can you use XML to register the receiver in this scenario?

See Also


The source code for this project is in the Android Cookbook repository, http://github.com/IanDarwin/Android-Cookbook-Examples/tree/master/LocalBroadcastDemo