Search code examples
c#xamarin.androidbroadcastreceiverlocalbroadcastmanager

How to use Xamarin Android LocalBroadcastManager


I've been searching for a way to send a local message within my app and found a tutorial from the Xamarin website on Broadcast Receivers here, more specifically at the bottom of the web page concerning LocalBroadcastManager. I followed the tutorial and read the page a few times but my BroadcastReceiver class still isn't receiving anything when I send a message. I've hit a lot of the questions concerning LocalBroadcastManager for java, but can't seem to figure out what's missing for C#.

This is the code that's triggering a sent message:

Intent intent = new Intent("dirty");
intent.PutExtra("dirtyAppCount", dirtyAppCount);
LocalBroadcastManager.GetInstance(Context).SendBroadcast(intent);

Here's where I'm registering my receiver in OnResume():

_dirtyMessageReceiver = new DirtyBroadcastReceiver();
RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));

Unregistering receiver in OnPause():

UnregisterReceiver(_dirtyMessageReceiver);

And here's my receiver class:

[BroadcastReceiver(Enabled = true, Exported = false)]
public class DirtyBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        int dirtyAppCount = intent.GetIntExtra("dirtyAppCount", 0);
        OnMessageReceived?.Invoke(this, new MessageArgs(dirtyAppCount));
    }
}

Solution

  • There are two issues with this code. First, you should use be registering the Receiver with the LocalBroadcastManager:

     _dirtyMessageReceiver = new DirtyBroadcastReceiver();
    RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));
    

    Should be

     _dirtyMessageReceiver = new DirtyBroadcastReceiver();
     LocalBroadcastManager.GetInstance(this).RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));
    

    Secondly, the Unregistering of the Receiver should be one against the LocalBroadcastManager as well:

    UnregisterReceiver(_dirtyMessageReceiver);
    

    becomes

    LocalBroadcastManager.GetInstance(this).UnregisterReceiver(_dirtyMessageReceiver);