Xamarin.Forms 是一个用于构建跨平台移动应用程序的框架,它允许开发者使用 C# 和 XAML 来编写一次代码,然后在多个平台上运行。Firebase Cloud Messaging (FCM) 是 Google 提供的一个服务,用于向移动设备发送通知和消息。
Xamarin.Forms: 是一个开源的 UI 工具包,用于构建跨平台的移动应用程序。
Firebase Cloud Messaging (FCM): 是 Google 的云消息传递服务,允许开发者向他们的应用程序发送通知和消息。
Android 应用程序状态:
当应用程序在前台、后台和滑动关闭时,FCM 的行为可能会有所不同:
为了确保在所有状态下都能正确处理 FCM 消息,可以采取以下步骤:
// 在 AppDelegate.cs 中初始化 FCM
public override void OnCreate()
{
FirebaseApp.InitializeApp(this);
base.OnCreate();
}
public class FirebaseMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
// 处理前台消息
if (!string.IsNullOrEmpty(message.Notification?.Body))
{
// 显示自定义通知或者处理数据
}
}
public override void OnNewIntent(Intent intent)
{
// 处理从通知栏打开应用的情况
base.OnNewIntent(intent);
}
}
// 在发送通知时使用 PendingIntent
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, channelId)
.SetSmallIcon(Resource.Drawable.ic_launcher_foreground)
.SetContentTitle("FCM Message")
.SetContentText(message.Notification.Body)
.SetAutoCancel(true)
.SetPriority((int)NotificationPriority.High)
.setContentIntent(pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(0, notificationBuilder.Build());
确保在 AndroidManifest.xml 中注册服务:
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
通过上述步骤,可以确保无论应用程序处于何种状态,都能够正确地接收和处理 FCM 消息。
领取专属 10元无门槛券
手把手带您无忧上云