我的BroadcastReceiver没有接收到任何信息。很可能是我的设置出了问题,因为我在这方面找不到任何好的例子。 我需要让我的接收器在MainActivity中接收一些东西,并更改一个视图。 我在Android项目中几乎有相同的代码,在那里它可以工作,但是在Xamarin中似乎实现BroadcastReceivers有点不同(在Android中,我可以像对象一样创建新的BroadcastReceiver,但在Xamarin或C#中,我似乎必须自己创建类,因此不能直接引用视图)。 如果我让它起作用,我也会为每个人发布一个完整的工作示例。
以下是我尝试设置的方式:
以下是我尝试设置的方式:
[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;
}
}
[BroadcastReceiver]
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");
((MainActivity)context).SetButtonText(text);
InvokeAbortBroadcast();
}
}
在我的IntentService中,我有这个方法实际运行,但从未到达我的接收器。
private void SendBroadcast(double lat, double lng, string activity)
{
Intent intent = new Intent("test");
intent.PutExtra("title", "Updated");
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
}
这段代码与我在工作中使用的Android代码基本相同(只是微调了BroadcastReceiver并进行了一些小的调整以使其编译)。
有谁能看出问题在哪里吗?
编辑 最终,我让整个事情都正常工作了。您可以查看我的答案以获取完整而清晰的示例。