#xamarin.forms #push-notification
#xamarin.forms #push-уведомление
Вопрос:
Я использую следующую полезную нагрузку уведомления для отправки push-уведомлений на мое Android-устройство с помощью postman.
{
"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. Пожалуйста, обратитесь к следующей ссылке firebase.google.com/docs/cloud-messaging/android /…
Ответ №1:
Я обрабатываю нажатие уведомления следующим образом. Загрузка страницы обрабатывается в App.xaml.cs.
При 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));
}
В 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());
}
}