How to use Xamarin Android LocalBroadcastManager

Viewed 1842

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));
    }
}
2 Answers
Related