c# - FCM 和 xamarin.android - 广播接收器不起作用
问题描述
我在 xamarin.android 中的广播接收器有问题。无法让它工作。
我在我的应用程序中有通知工作,我想在收到通知后更改我的应用程序中的一些内容(例如 Toast 消息或更改按钮的图标)但它不起作用。我不知道我做错了什么,也找不到解决方案,因为所有主题都与 Java 相关。当用户收到通知时,我需要一些东西、事件或广播接收器来触发,然后我想在我的 MainActivity 中做一些事情。
所以,这就是代码。
广播接收器类:
[BroadcastReceiver(Enabled = true, Exported = false)]
public class MyMessageReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
bool messageReceived = intent.GetBooleanExtra("messageReceived", false);
}
}
OnMessageReceived 方法:
{
base.OnMessageReceived(message);
SendNotification(message.GetNotification().Body);
LocalBroadcastManager broadcaster = LocalBroadcastManager.GetInstance(this);
Intent intent = new Intent("message");
intent.PutExtra("messageReceived", true);
broadcaster.SendBroadcast(intent);
}
以及 OnResume 和 OnPause 方法:
protected override void OnResume()
{
base.OnResume();
LocalBroadcastManager.GetInstance(this).RegisterReceiver(myReceiver, new IntentFilter("message"));
RegisterReceiver(myReceiver, new IntentFilter("message"));
}
protected override void OnPause()
{
base.OnPause();
LocalBroadcastManager.GetInstance(this).UnregisterReceiver(myReceiver);
}
我不知道如何在 MainActivity 的 OnCreate 方法中接收该信息?我试过了
messageReceived = Intent.GetBooleanExtra("messageReceived", false);
if (messageReceived)
{
Toast.MakeText(this, "new notification", ToastLength.Long).Show();
}
但这不起作用, messageReceived 为空。
解决方案
我知道这有点太晚了,但迟到总比没有好:
在分析了 firebase 消息后,我为此目的做了一个合适的解决方法:
当您的应用程序在后台时,默认情况下会在接收推送通知时调用句柄意图方法:
public override void HandleIntent(Intent p0)
{
base.HandleIntent(intent);
//Your code to know that you received a notification (backgrounnd)
// Use shared preference for this
}
不知道如何使用共享首选项检查此。
有关句柄意图如何工作的更多信息,请在此处查看我的答案。
当应用程序在前台时,您可以简单地使用消息接收方法,如下所示:
public override void OnMessageReceived(Context context, Intent intent)
{
//Your code to know that you received a notification (backgrounnd)
// Use shared preference for this
}
然后,无论您需要在哪里使用它,您都可以获得一个标志或计数或任何使用共享首选项的东西。
如有任何疑问,请回复!
推荐阅读
- typescript - NestJS - 如何使用 @Body() 装饰器访问帖子正文?
- mysql - MySQL通过同一列中的匹配值更新表
- python - 当我结束我的应用程序并重新运行它时,列表会清除
- flutter - 如何使用颤振获取 android/ios 设备的代理设置?
- c# - 如何:通过控制台捕获 void 方法的输出?
- php - 是否可以通过输入搜索嵌入谷歌地图?
- java - SFTP 连接错误
- python - Keras安装错误
- c++ - 当我尝试函数重载时数组得到垃圾值
- ios - iPhone 6S vs 7+ vs X vs iPad Pro 的 FaceTime 摄像头的 FPS 是多少?