加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – BroadcastReceiver不接收广播

发布时间:2020-12-15 04:14:36 所属栏目:百科 来源:网络整理
导读:我的BroadcastReceiver没有收到任何东西.很可能是我的设置错了,因为我无法在此找到任何好的例子.我需要我的接收器在我的MainActivity中接收一些东西,并更改一个视图.我在 Android项目中有几乎相同的代码,并且它在这里工作,但是在Xamarin中,BroadcastReceiver
我的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和微调以使其编译).

任何人都可以看到什么错?

编辑
最后得到了这整件事.你可以看到我的答案,一个完整,干净的例子.

解决方法

本地

您将接收器注册为全局,但通过LocalBroadcastManager发送意图.如果你想使用这个经理你应该像这样注册你的接收器:

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

您可以找到有关LocalBroadcastManager here的更多信息.

全球

或者,如果要使用全局广播,则应按类型创建意图:

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

并通过android Context(在您的服务中)发送:

this.SendBroadcast(intent);

您也可以使用intent with action,但它需要接收器上的IntentFilter属性:

[IntentFilter(new []{ "test" })]
[BroadcastReceiver]
public class LocationBroadcastReciever : BroadcastReceiver { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读