如何处理 Firebase 通知,即 Android 中的通知消息和数据消息

Fre*_*Ali 2 xamarin.android firebase xamarin firebase-cloud-messaging

当用户处于前台和后台时,使用 Xamarin Android 在 firebase 中处理通知消息和数据消息的最佳方法是什么?

另外,如何获取通知数据,例如特定通知的文本?

PS:我访问过以下线程,但没有一个真正有帮助:

当设备屏幕关闭时如何处理 firebase 通知?

Firebase 通知和数据

在 Android 托盘上显示 firebase 通知数据消息

Fre*_*Ali 5

好吧,我找到了自己问题的答案,因此我将答案发布给正在 xamarin 中寻找 firebase 集成的人。

  • Xamarin.Firebase.Messaging将包安装到您的项目中。

  • 将以下代码添加到您的manifest.xml以接收firebase通知。

    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在要从 firebase 获取注册令牌,请添加一个类文件并向其中添加以下代码:

    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
      public override void OnTokenRefresh()
       {
            const string TAG = "MyFirebaseIIDService";
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(TAG, "Refreshed token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);
        }
       void SendRegistrationToServer(string token)
        {
           // Add custom implementation, as needed.
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这里FirebaseInstanceId.Instance.Token获取当前设备的实例令牌,也可以使用发送令牌的方法SendRegistrationToServer将令牌发送到服务器。

  • 现在添加另一个类来处理前台通知

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
       // private string TAG = "MyFirebaseMsgService";
          public override void OnMessageReceived(RemoteMessage message)
       {
           base.OnMessageReceived(message);
           string messageFrom = message.From;
           string getMessageBody = message.GetNotification().Body;
           SendNotification(message.GetNotification().Body);
       }
    void SendNotification(string messageBody)
    {
        try
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
    
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                .SetContentTitle("Title")
                .SetContentText(messageBody)
                .SetAutoCancel(true)
                .SetContentIntent(pendingIntent);
    
            NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
        catch (Exception ex)
        {
    
        }
       }
     }
    
    Run Code Online (Sandbox Code Playgroud)

这里该方法SendNotification用于显式向系统托盘发送通知,因为设备处于前台时的推送通知不会自动显示在系统托盘中。

  • 当设备处于后台或自动生成终止通知并且默认情况下加载主启动器活动时,要从后台通知获取数据,您需要使用意图,如下所示(在您的主启动器活动上):

      if (Intent.Extras != null)
        {
            foreach (var key in Intent.Extras.KeySet())
            {
                var value = Intent.Extras.GetString(key);
                Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
            }
        }
    
    Run Code Online (Sandbox Code Playgroud)
  • 此外,如果 google play 服务不是最新的,此代码可能会使您的应用程序崩溃,因此要检查 google play 服务是否可用,请执行以下操作:

    public bool IsPlayServicesAvailable()
    {
        int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.Success)
        {
            if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
                msgText.Text = GoogleApiAvailability.Instance.GetErrorString(resultCode);
            else
            {
                msgText.Text = "This device is not supported";
                Finish();
            }
            return false;
        }
        else
        {
            msgText.Text = "Google Play Services is available.";
            return true;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

检查以下链接,了解有关如何将项目添加到 Firebase 控制台的信息:

https://developer.xamarin.com/guides/android/data-and-cloud-services/google-messaging/remote-notifications-with-fcm/ \

更新

  • 在 Android Oreo 最近进行更改后,您必须将通知添加到通道中,因为您需要在 MainActivity 中创建通知通道,如下所示:

    void CreateNotificationChannel()
    {
       if (Build.VERSION.SdkInt < BuildVersionCodes.O)
       {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification 
        // channel on older versions of Android.
        return;
       }
    
      var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
                  {
                      Description = "Firebase Cloud Messages appear in this channel"
                  };
    
    var notificationManager = (NotificationManager) GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
    }
    
    Run Code Online (Sandbox Code Playgroud)

在 MainActivity 的 OnCreate 方法中调用此方法。