Search code examples
broadcastreceiveripclocalbroadcastmanager

Android: when Activity receives a broadcast how to detect if sender is the Activity itself?


My Android app uses LocalBroadcastManager and BroadcastReceiver to communicate between activities. How do you have an activity detect when it is receiving an Intent that originated from itself rather than another Activity? In other words, how do you get the broadcast caller and ignore it if it equals this.


Solution

  • I'm not aware of if there's a specific way of doing this, but, I would add a specific action to my Intent that is being broadcast. It could look like this:

    Intent broadcastIntent = new Intent(MyClass.class.getName());
    sendBroadcast(broadcastIntent);
    

    Then when you receive the broadcast, you'll simply just check for the specific action:

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(MyClass.class.getName()) {
            // Ignore the broadcast as it's the caller calling itself...
        } else {
            // Do something with the broadcast...
        }
    }
    

    There might be other ways to do this (like just putting extras into the Intent and then reading it out in the onReceive method), but I find this to be a really simple way of getting who the caller is.