如何使用 Xamarin Android LocalBroadcastManager

How to use Xamarin Android LocalBroadcastManager

我一直在寻找一种在我的应用程序中发送本地消息的方法,并在 Xamarin 网站上找到了关于广播接收器的教程 here,更具体地说,在有关 LocalBroadcastManager 的网页底部。我按照教程阅读了几次页面,但是当我发送消息时我的 BroadcastReceiver class 仍然没有收到任何信息。我遇到了很多关于 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);

这是我的接收器class:

[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));
    }
}

这段代码有两个问题。首先,您应该使用 LocalBroadcastManager:

注册接收器
 _dirtyMessageReceiver = new DirtyBroadcastReceiver();
RegisterReceiver(_dirtyMessageReceiver, new IntentFilter("dirty"));

应该是

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

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

UnregisterReceiver(_dirtyMessageReceiver);

变成

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

您需要为 these.For 添加一个广播接收器,将 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);