Xamarin Forms: открыть страницу содержимого, когда нажмите push-уведомление с помощью FirebasePushNotificationPlugin - PullRequest
0 голосов
/ 18 апреля 2019

Я использую следующую полезную нагрузку для отправки push-уведомлений на устройство Android с помощью почтальона.

{
    "to" : "device_key",
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification",
     "sound": "default"
 },
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

Уведомления принимаются на мое устройство и OnMessageReceived() запускаются, только когда приложение находится на переднем плане.Когда приложение находится в фоновом режиме OnMessageReceived не запускается и не запускается при нажатии на уведомление.

Я установил FirebasePushNotificationPlugin и добавил события уведомления в конструкторе приложений, как показано ниже.

CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
{
      System.Diagnostics.Debug.WriteLine("Received");
};

CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
{
    System.Diagnostics.Debug.WriteLine("Opened");
    foreach (var data in p.Data)
     {
         System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
     }
     if (!string.IsNullOrEmpty(p.Identifier))
     {
         System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
     }
 };

Но при получении или нажатии на уведомление эти коды не срабатывают.

В одном потоке я обнаружил, что вышеуказанные события инициируются, когда вы отправляете только сообщение с данными, не должны отправляться уведомления, если вы хотите использовать этот обработчик событий.

Но если я отправляю сообщения с данными, на мое устройство не поступают только уведомления.Ниже приведены полезные данные уведомлений для сообщений данных.

{
    "to" : "device_key",
 "collapse_key" : "type_a",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

Мне нужно открыть страницу содержимого в PCL при нажатии на уведомление.Но OnNotificationReceived или OnNotificationOpened не срабатывают.Так чего же мне не хватает в этой реализации?

1 Ответ

0 голосов
/ 01 мая 2019

Я обрабатываю уведомление, нажав следующим образом.Загрузка страницы обрабатывается в App.xaml.cs.

On OnCreate ():

//Background or killed mode
if (Intent.Extras != null)
{
    foreach (var key in Intent.Extras.KeySet())
    {
        var value = Intent.Extras.GetString(key);
        if (key == "webContentList") 
        {
            if (value?.Length > 0)
            {
                isNotification = true;
                LoadApplication(new App(domainname, value));
            }
        }
    }
}
//Foreground mode
if (FirebaseNotificationService.webContentList.ToString() != "")
{
    isNotification = true;
    LoadApplication(new App(domainname, FirebaseNotificationService.webContentList.ToString()));
    FirebaseNotificationService.webContentList = "";
}

//Normal loading
if (!isNotification)
{
    LoadApplication(new App(domainname, string.Empty));
}

On FirebaseNotificationService:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class FirebaseNotificationService : FirebaseMessagingService
{
    public static string webContentList = "";
    public override void OnMessageReceived(RemoteMessage message)
    {
        base.OnMessageReceived(message);
        webContentList = message.Data["webContentList"];

        try
        {
            SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error:>>" + ex);
        }
    }

    public void SendNotificatios(string body, string Header)
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
                        .SetContentTitle(Header)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetContentText(body)
                        .SetAutoCancel(true)
                        .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
        else
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
                        .SetContentTitle(Header)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetContentText(body)
                        .SetAutoCancel(true)
                        .SetContentIntent(pendingIntent)
                        .SetChannelId(Utils.CHANNEL_ID);

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return;
            }

            var channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.High)
            {
                Description = "Firebase Cloud Messages appear in this channel"
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
    }
...