如何在 Xamarin Forms 中保存通过应用推送通知接收的数据

How to save data received via push notification for an app in Xamarin Forms

我正在使用 Firebase 云消息传递。

当我收到推送通知时,我有两种情况:

  1. 当应用程序在前台(或运行)时,我使用以下代码保存数据
  public override void OnMessageReceived(RemoteMessage message)
        {
            var body = message.GetNotification().Body;
            var title = message.GetNotification().Title;
            string[] notificationMessage = { title, body };
            MessagingCenter.Send<object, string[]>(this, Constants.TOPIC, notificationMessage);
            Preferences.Set("title", message[0]);
            Preferences.Set("body", message[1]);
            SendNotification(title, body, message.Data);
        }

以上代码运行良好,数据已保存在首选项中。

  1. 但是当它不是 运行 时,当我收到通知时它不会被保存。 有什么办法可以在 Xamarin FormsAndroid 和 iOS 中做到这一点

UPDATED<<<<<<<

#FirebaseMessageService
 public class UWTFirebaseMessagingService : FirebaseMessagingService
    {
        public override void OnMessageReceived(RemoteMessage message)
        {
            var body = message.GetNotification().Body;
            var title = message.GetNotification().Title;
            string[] notificationMessage = { title, body };
            MessagingCenter.Send<object, string[]>(this, Constants.TOPIC, notificationMessage);
            SendNotification(title, body, message.Data);
        }

        void SendNotification(string messageTitle, string messageBody, IDictionary<string, string> data)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.PutExtra("title", messageTitle);
            intent.PutExtra("body", messageBody);
            intent.AddFlags(ActivityFlags.ClearTop);
            foreach (var key in data.Keys)
            {
                intent.PutExtra(key, data[key]);
            }

            var pendingIntent = PendingIntent.GetActivity(this,
                                                          MainActivity.NOTIFICATION_ID,
                                                          intent,
                                                          PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_ID)
                                      .SetSmallIcon(Resource.Drawable.icon)
                                      .SetContentTitle(messageTitle)
                                      .SetContentText(messageBody)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(Constants.NOTIFICATION_ID, notificationBuilder.Build());
        }
    }

主要活动

 protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            RequestPermissions(Permission, RequestId);
            HtmlLabelRenderer.Initialize();
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Xamarin.FormsMaps.Init(this, savedInstanceState);
            GAService.GetGASInstance().InitializeNativeGAS(this);
            CreateNotificationChannel();
            FirebaseMessaging.Instance.SubscribeToTopic(Constants.TOPIC);
            LoadApplication(new App());
            if (Intent.Extras != null)
            {
                foreach (var key in Intent.Extras.KeySet())
                {
                    if (key == "title")
                    {
                        var value = Intent.Extras.GetString(key);
                        Preferences.Set("title", value);
                    }
                    else if (key == "body")
                    {
                        var value = Intent.Extras.GetString(key);
                        Preferences.Set("body", value);
                    }
                }
            }
        }
       

        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(Constants.CHANNEL_ID,
                                                  Constants.CHANNEL_NAME,
                                                  NotificationImportance.Default)
            {

                Description = Constants.CHANNEL_DESCRIPTION
            };

            var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }

        //for foreground and backgrounded state
        protected override void OnNewIntent(Intent intent)
        {

            if (intent != null)
            {
                var title = intent.GetStringExtra("title");
                var body = intent.GetStringExtra("body");

                Preferences.Set("title", title);
                Preferences.Set("body", body);
            }

        }
    }

嗨,我 运行 这几天有类似的问题 ago.According 到 firebase 文档 Documentation 可以创建两种类型的通知。

  1. 通知消息
  2. 数据消息

如果我们正在发送通知消息,并且我们的应用已关闭,OnMessageReceived 将永远不会调用。

如果我们正在发送数据消息,那么当我们的应用程序在前台或后台或关闭时 OnMessageReceived 将调用。

因此,如果您的应用关闭,您可以使用 Intent 管理通知消息。

在您的 Firebase 消息服务中

public static string title = "";
public static string body = "";

 public override void OnMessageReceived(RemoteMessage message)
    {
            base.OnMessageReceived(message);
            var body = message.GetNotification().Body;
            var title = message.GetNotification().Title;
            string[] notificationMessage = { title, body };
            MessagingCenter.Send<object, string[]>(this, Constants.TOPIC, notificationMessage);  
            SendNotification(title, body, message.Data);
     }  


      private void SendNotification(string messageBody, IDictionary<string, string> data)
     {

        var intent = new Intent(this, typeof(MainActivity));
        intent.PutExtra("title", title);
        intent.PutExtra("body", body);

        intent.AddFlags(ActivityFlags.ClearTop);
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }
        var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);
        var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID).SetSmallIcon(Resource.Drawable.ic_launcher).SetContentTitle("your notification").SetContentText(messageBody).SetAutoCancel(true).SetContentIntent(pendingIntent);
        var notificationManager = NotificationManagerCompat.From(this); notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
  }

在你的主要 Activity

 protected override void OnCreate(Bundle savedInstanceState)
        {

           LoadApplication(new App());

          //  For killed app state
             if (Intent.Extras != null)
             {
                foreach (var key in Intent.Extras.KeySet())
                {
                    if (key != null)
                    {
                        if(key== "title")
                        {
                            var value = Intent.Extras.GetString(key);
                            Preferences.Set("title", value);                                                    
                        }      
                       else if(key== "body")            
                       {
                            var value = Intent.Extras.GetString(key);
                            Preferences.Set("body", value); 
                       }

                }
            }   

        }
    }
    //after oncreate
    //for foreground and backgrounded state
    protected override void OnNewIntent(Intent intent)
        {

            if (intent != null)
            {
                var title = intent.GetStringExtra("title");
                var body = intent.GetStringExtra("body");

              Preferences.Set("title", title);   
              Preferences.Set("body", body); 
            }

        }