BroadcastReceiver无法接收广播

时间:2016-06-02 13:56:31

标签: c# 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并进行了微调,以使其编译)。

谁能看到什么错?

修改 最后得到了这整件事。你可以看到我的答案,以获得一个完整,干净的例子。

3 个答案:

答案 0 :(得分:7)

本地

您将接收器注册为全局,但通过LocalBroadcastManager.GetInstance(this).RegisterReceiver(lbr, filter); 发送意图。如果你想使用这个经理,你应该注册你的接收器:

LocalBroadcastManager

您可以找到有关var intent = new Intent(this, typeof(LocationBroadcastReciever)); here

的更多信息

全局

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

Context

并通过android this.SendBroadcast(intent); (在您的服务中)发送:

IntentFilter

此外,您可以将意图与行动结合使用,但接收器上需要[IntentFilter(new []{ "test" })] [BroadcastReceiver] public class LocationBroadcastReciever : BroadcastReceiver { ... } 属性:

<!-- Configure SystemJS -->
<script>System.config({ baseURL: '/' });</script>
<script src="/appScripts/config.js"></script>
<script>
    System.import('appScripts/boot').catch(console.log.bind(console));
</script>

答案 1 :(得分:2)

为了将来的搜索结果,这里有一个干净的示例,我的代码带有工作的BroadcastReceiver

// ** MainActivity
namespace GetLocation.Droid
{
    [Activity(Label = "GetLocation.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        //I initialize my view(s) here to access them from outside of OnCreate().
        Button button;
        //I found this in an Android BroadcastReceiver example of how to access the MainActivity from the BroadcastReceiver.
        private static MainActivity ins;
        public static MainActivity getInstace()
        {
            return ins;
        }
        protected override void OnCreate(Bundle bundle)
        {

            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            button = FindViewById<Button>(Resource.Id.myButton);
            ins = this;

            button.Click += delegate
            {
                Intent intent = new Intent(this, typeof(MyIntentService));
                StartService(intent);
            };

            LocationBroadcastReciever lbr = new LocationBroadcastReciever();
            LocalBroadcastManager.GetInstance(this).RegisterReceiver(lbr, new IntentFilter("test"));

        }

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

    [BroadcastReceiver]
    [IntentFilter(new[] { "test" })]
    public class LocationBroadcastReciever : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string text = intent.GetStringExtra("title");
            MainActivity.getInstace().SetButtonText(text);
        }
    }
}

在我的IntentService中

namespace GetLocation.Droid
{
    [Service]
    [IntentFilter(new String[] { "com.mytos.MyIntentService" })]
    public class MyIntentService : IntentService
    {

        protected override void OnHandleIntent(Intent intent)
        {
            SendBroadcast("My message");
        }

        private void SendBroadcast(string message)
        {
            //Here you can of course send whatever variable you want. Mine is a string
            Intent intent = new Intent("test");
            intent.PutExtra("title", message);
            LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
        }
    }
}

答案 2 :(得分:1)

有几件事:

首先,您需要接收器上的[IntentFilter]。所以它应该看起来像....

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new [] { "test" })]
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). */
        string text = intent.GetStringExtra("title");
        ((MainActivity)context).SetButtonText(text);
        InvokeAbortBroadcast();
    }
}

那可以让你解决问题。

其次,您应该注册和取消注册接收者。因此,您应该在OnResume注册并注销OnPause

[Activity(Label = "GetLocation.Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    LocationBroadcastReciever _lbr;
    Button button;

    protected override void OnCreate(Bundle bundle)
    {
        // ... various OnCreate() code
    }

    protected override void OnResume()
    {
        base.OnResume();
        _lbr = new LocationBroadcastReciever();
        RegisterReceiver(lbr, new IntentFilter("test"));
    }

    protected override void OnPause()
    {
        UnregisterReceiver(_lbr);
        base.OnPause();
    }

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

注意:这些更改是我在您的代码和工作广播接收器的代码之间看到的不同之处。无论我的改变是否必要,我都不完全确定。