如何使用Xamarin Android LocalBroadcastManager

时间:2017-07-19 14:15:06

标签: c# xamarin.android broadcastreceiver localbroadcastmanager

我一直在寻找一种在我的应用程序中发送本地消息的方法,并在Xamarin网站上找到了广播接收器here的教程,更具体地说是在有关LocalBroadcastManager的网页底部。我按照教程阅读了几次页面,但是当我发送消息时,我的BroadcastReceiver类仍然没有收到任何内容。我已经遇到了很多关于java的LocalBroadcastManager的问题,但似乎无法弄清楚C#缺少什么。

这是触发已发送消息的代码:

Intent intent = new Intent("dirty");
intent.PutExtra("dirtyAppCount", dirtyAppCount);
LocalBroadcastManager.GetInstance(Context).SendBroadcast(intent);

我在OnResume()注册我的接收器的地方:

_dirtyMessageReceiver = new DirtyBroadcastReceiver();
RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));

在OnPause()中取消注册接收器:

UnregisterReceiver(_dirtyMessageReceiver);

这是我的接收器课程:

[BroadcastReceiver(Enabled = true, Exported = false)]
public class DirtyBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        int dirtyAppCount = intent.GetIntExtra("dirtyAppCount", 0);
        OnMessageReceived?.Invoke(this, new MessageArgs(dirtyAppCount));
    }
}

2 个答案:

答案 0 :(得分:2)

此代码存在两个问题。首先,您应该使用LocalBroadcastManager注册接收器:

 _dirtyMessageReceiver = new DirtyBroadcastReceiver();
RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));

应该是

 _dirtyMessageReceiver = new DirtyBroadcastReceiver();
 LocalBroadcastManager.GetInstance(this).RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));

其次,接收方的取消注册也应该是针对LocalBroadcastManager的注册:

UnregisterReceiver(_dirtyMessageReceiver);

变为

LocalBroadcastManager.GetInstance(this).UnregisterReceiver(_dirtyMessageReceiver);

答案 1 :(得分:0)

你需要为这些添加一个广播接收器。例如,将Android.Content.Intent设置为ActionTimeTick,这样只要时间改变,android os就会广播消息(一个android意图)。

[BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionTimeTick })]
    public class GridStartBroadcastReceiver : BroadcastReceiver
    {
        public static readonly string GRID_STARTED = "GRID_STARTED";
        public override void OnReceive(Context context, Intent intent)
        {
           if (intent.Action == GRID_STARTED)
            {
         //your logic
            }
        }
    }

您需要先注册广播接收器。将这些代码添加到oncreate方法以注册广播接收器。

IntentFilter filter = new IntentFilter(GridStartBroadcastReceiver.GRID_STARTED);
            filter.AddCategory(Intent.CategoryDefault);
            _receiver = new GridStartBroadcastReceiver();
            RegisterReceiver(_receiver, filter);

接下来将广播发送给广播接收器。

//calling
                    Intent BroadcastIntent = new Intent(this, typeof(MainActivity.GridStartBroadcastReceiver));
                    BroadcastIntent.SetAction(MainActivity.GridStartBroadcastReceiver.GRID_STARTED);
                    BroadcastIntent.AddCategory(Intent.CategoryDefault);
                    SendBroadcast(BroadcastIntent);