How to Restrict Broadcast within an Application in Android


Whenever we initiate an event through a broadcast in our application then that broadcast is announced system wide. So any application who is listening to the broadcast with the same action and category that our application is broadcasting  then that application will also be notified about the broadcast.

 Is there a way to restrict broadcasts within the application so that the broadcast will be announced within my application? Well LocalBroadcastManager is the answer to that.

Below is a code snippet to initiating a broadcast from our application:

Intent lObjIntent = new Intent();
lObjIntent.addCatagory(Intent.CATAGORY_DEFAULT);
lObjIntent.setAction(“com.myexample.demo”);
sendBroadcast(lObjIntent);

With the above code any application installed on the same android device with BroadcastReceiver with action “com.myexample.demo” will be able to receive broadcast.

How to restrict the broadcast so that only my application’s broadcast receiver will be notified?

LocalBroadcastManager lObjLocalBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());

Intent lObjIntent= new Intent();
lObjIntent.addCatagory(Intent.CATAGORY_DEFAULT);
lObjIntent.setAction(“com.myexample.demo”);
lObjLocalBroadcastManager.sendBroadcast(lObjIntent);

In the above code we have used the instance of LocalBroadcastManager to achieve our goal to send the broadcast within our application. So the same broadcast with the same event will not be delivered to other applications.

Leave A Comment

Your email address will not be published. Required fields are marked *