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

时间:2017-12-15 06:23:42

标签: firebase xamarin xamarin.android firebase-cloud-messaging

使用Xamarin Android处理firebase中的通知消息和数据消息的最佳方法是什么,而用户位于Foreground和Background中?

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

PS:我访问了以下主题,实际上没有人帮助过:

When device screen off then how to handle firebase notification?

Firebase Notification and Data

Display firebase notification data-message on Android tray

1 个答案:

答案 0 :(得分:1)

好吧,我找到了自己问题的答案,所以我正在为那些正在寻找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>
    
  • 现在从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.
        }
    }
    

    此处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)
        {
    
        }
       }
     }
    

此处方法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);
            }
        }
    
  • 此外,如果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;
        }
    }
    

有关如何将项目添加到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);
    }
    

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