mat*_*d91 7 c# android broadcastreceiver xamarin
我的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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的IntentService中,我有这个实际运行的方法,但从未到达我的接收器.
private void SendBroadcast(double lat, double lng, string activity)
{
Intent intent = new Intent("test");
intent.PutExtra("title", "Updated");
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
}
Run Code Online (Sandbox Code Playgroud)
这与我工作的Android中的代码几乎相同(只调整了BroadcastReceiver和微调以使其编译).
任何人都可以看到什么错?
编辑 终于完成了整个工作.你可以看到我的答案,一个完整,干净的例子.
您将接收器注册为全局,但通过发送意图LocalBroadcastManager.如果你想使用这个经理你应该像这样注册你的接收器:
LocalBroadcastManager.GetInstance(this).RegisterReceiver(lbr, filter);
Run Code Online (Sandbox Code Playgroud)
你可以找到更多关于LocalBroadcastManager 这里.
或者,如果要使用全局广播,则应按类型创建意图:
var intent = new Intent(this, typeof(LocationBroadcastReciever));
Run Code Online (Sandbox Code Playgroud)
并通过android Context(在您的服务中)发送:
this.SendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)
您也可以使用intent with action,但它需要IntentFilter接收器上的属性:
[IntentFilter(new []{ "test" })]
[BroadcastReceiver]
public class LocationBroadcastReciever : BroadcastReceiver { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6451 次 |
| 最近记录: |