Как сохранить данные, полученные с помощью уведомления pu sh для приложения в Xamarin Forms - PullRequest
1 голос
/ 07 апреля 2020

Я использую Firebase Cloud Messaging.

Когда я получаю уведомление pu sh, у меня есть два сценария ios:

  1. Когда приложение находится на переднем плане (или работает), я использую следующий код для сохранения data
  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);
        }

Приведенный выше код работает нормально, данные сохраняются в предпочтениях.

Но когда он не работает, то, когда я получаю уведомление, он не сохраняется. Есть ли способ сделать это в Android и iOS в формах Xamarin

ОБНОВЛЕНО <<< <<<< </p>

#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());
        }
    }

MainActivity

 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);
            }

        }
    }

1 Ответ

1 голос
/ 07 апреля 2020

Привет, я запустил эту похожую проблему несколько дней go. Согласно документации Firebase Документация Существует два типа уведомлений.

  1. Уведомления
  2. Сообщения данных

Если мы отправляем уведомления и наше приложение закрывается, OnMessageReceived никогда не будет вызываться.

Если мы отправляем сообщения данных, то когда наше приложение будет либо в фоновом режиме, либо в фоновом режиме, либо закрыто, вызовет OnMessageReceived.

Таким образом, вы можете управлять уведомлениями, если ваше приложение закрыто, используя намерения.

В ваша служба Firebase Messeging

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());
  }

в вашей основной деятельности

 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); 
            }

        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...