mathkid91 mathkid91 - 1 year ago 1184
Android Question

Xamarin BroadcastReceiver not receiving broadcast (Android)

My BroadcastReceiver does not receive anything. Most likely its my setup that is wrong, because I was not able to find any good examples on this. I need my receiver to receive something in my MainActivity, and change a View. I have almost the same code in an Android project, and here it is working, however BroadcastReceivers seems to be implemented a tiny bit differently in Xamarin (in Android, I can make a new BroadcastReceiver almost like an object, but in Xamarin, or C#, it seems I must make my own class and thus do not have the same possibilities to directly reference the views). If I get this to work, I will post a full working example for everyone too.

Here is how I have tried to set it up:

[Activity(Label = "GetLocation.Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
Button button;
protected override void OnCreate(Bundle bundle)
// ... various OnCreate() code

LocationBroadcastReciever lbr = new LocationBroadcastReciever();
RegisterReceiver(lbr, new IntentFilter("test"));


public void SetButtonText(string text)
button.Text = text;

public class LocationBroadcastReciever : BroadcastReceiver
public override void OnReceive(Context context, Intent intent)
/* My program never get this far, so I have not been able
to confirm if the bellow code works or not (its from
another example I saw). */
//EDIT: It does NOT work. See my answer for a working example
string text = intent.GetStringExtra("title");

And in my IntentService I have this method that actually runs, but never arrives at my receiver.

private void SendBroadcast(double lat, double lng, string activity)
Intent intent = new Intent("test");
intent.PutExtra("title", "Updated");

This is pretty much the same code as I have in my working Android (only tweaked the BroadcastReceiver and minor adjustments to make it compile).

Can anyone see whats wrong??

Finally got this whole thing to work. You can see my answer for a full, clean example.

Answer Source


You register receiver as global, but send intents via LocalBroadcastManager. If you want use this manager you should register your receiver like this:

LocalBroadcastManager.GetInstance(this).RegisterReceiver(lbr, filter);

You can find more about LocalBroadcastManager here.


Or if you want to use global broadcasts, you should create intent by type:

var intent = new Intent(this, typeof(LocationBroadcastReciever));

and send it via android Context (in your service):


Also you can use intent with action, but it requires IntentFilter attribute on your receiver:

[IntentFilter(new []{ "test" })]
public class LocationBroadcastReciever : BroadcastReceiver { ... }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download