xamarin формы: push-уведомление с использованием FCM.не может получить данные намерения из сообщения - PullRequest
0 голосов
/ 19 сентября 2019

Я использую push-уведомления firebase, после получения push-уведомлений мне нужно нажимать и получать новости и читать их.тело запроса к fcm:

{
    To = "/topics/all",
    Data = new Notification
    {
        Title = news.Title,
        Body = news.Body,
        SerializedNews = JsonConvert.SerializeObject(news)
    },
}

MessagingService.cs

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MessagingService : FirebaseMessagingService
{
    private readonly string NOTIFICATION_CHANNEL_ID = "com.timelysoft.SmartClub";

    public override void OnMessageReceived(RemoteMessage message)
    {
        if (!message.Data.GetEnumerator().MoveNext())
            SendNotification(message.GetNotification().Title, message.GetNotification().Body, null);
        else
            SendNotification(message.Data);
    }

    private void SendNotification(IDictionary<string, string> data)
    {
        string title, body, serializedNews;
        data.TryGetValue("title", out title);
        data.TryGetValue("body", out body);
        data.TryGetValue("SerializedNews", out serializedNews);
        SendNotification(title, body, serializedNews);
    }

    private void SendNotification(string title, string body, string news)
    {
        NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification Channel",
                Android.App.NotificationImportance.Default);
            notificationChannel.Description = "GGDescription";
            notificationChannel.EnableLights(true);
            notificationChannel.LightColor = Color.Blue;
            notificationChannel.SetVibrationPattern(new long[] { 0, 1000, 500, 1000 });

            notificationManager.CreateNotificationChannel(notificationChannel);
        }

        Intent mainActivityIntent = new Intent(this, typeof(MainActivity));
        /* 
        here i put data in intent and start 
        mainactivity where I show data in new Page
        */
        mainActivityIntent.PutExtra("News", news);
        PendingIntent pendingIntent = PendingIntent.GetActivity(this, 100, mainActivityIntent, 0);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notificationBuilder.SetAutoCancel(true)
            .SetDefaults(-1)
            .SetWhen(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
            .SetContentTitle(title)
            .SetContentText(body)
            .SetSmallIcon(Resource.Drawable.icon)
            .SetContentInfo("info")
            .SetContentIntent(pendingIntent);
        notificationManager.Notify(new Random().Next(), notificationBuilder.Build());

    }
}

mainactivity.cs

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

        base.OnCreate(bundle);

        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;

        global::Xamarin.Forms.Forms.Init(this, bundle);
        DisplayCrashReport();

        CachedImageRenderer.Init();

        App app = new App();
        if (Intent.Extras != null)
        {
            foreach (var key in Intent.Extras.KeySet())
            {
                var value = Intent.Extras.GetString(key);
                Log.Debug("INTENT_KEY", key);
                Log.Debug("INTENT_VALUE", value);
                if (key == "News")
                {
                    if (value?.Length > 0)
                    {
                        /*
                        here code show data of comming news
                        */
                        News news = JsonConvert.DeserializeObject<News>(value);
                        App.MasterDetailPage.ShowPushNotificationInfo(news);
                    }
                }
            }
        }
        LoadApplication(app);

        TelephonyManager tm = (TelephonyManager) GetSystemService(TelephonyService);
        //App.SimSerialNumer = tm.SimSerialNumber;
        FirebaseMessaging.Instance.SubscribeToTopic("all");

        //Log.Debug("FIREBASETOKEN", FirebaseInstanceId.Instance.Token);
    }

, если я создаю приложение и начинаю отлаживать всевсе в порядке, если я получаю push-уведомление в первый раз, я могу отладить messagingservice.cs.и объект новости в порядке.но если я отправляю push-уведомление во второй раз, я не могу отлаживать службу сообщений при получении push-уведомления: не работает совместимый код

И после этого я получаю правильное название и текст push-уведомления, но новости содержатданные, отправленные первымиКак отладить службу сообщений?И почему поля заголовка и тела в порядке, а новостной объект неправильный?

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