Мне интересно, в каком классе я могу указать, как обрабатывать уведомление, которое отправляется, когда приложение закрыто или находится в фоновом режиме. Прямо сейчас я получаю уведомления локально, которые затем запускают мой метод SendLocalNotification
, чтобы структурировать его так, как я хотел бы, и это то, что я хочу, чтобы происходило с уведомлениями, когда приложение закрыто или в фоновом режиме тоже. Я все еще получаю фоновые уведомления, но они не запускают код, структурирующий то, как он должен выглядеть.
Я немного покопался и прочитал несколько вещей о переопределении метода для обработки удаленных уведомлений, но не смог Можно найти хороший пример или даже метод Speci c для переопределения.
Вот мое OnMessageReceived переопределение в моем классе FirebaseService (игнорируйте код, который выглядит из место. Я возился с вещами):
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
string messageBody = string.Empty;
if (message.GetNotification() != null)
{
switch (message.GetNotification().Title)
{
case "Load Matched":
break;
}
messageBody = message.GetNotification().Body;
}
else
{
messageBody = message.Data.Values.First();
}
try
{
MessagingCenter.Send(messageBody, "Update");
}
catch (Exception e)
{
}
SendLocalNotification(messageBody);
}
А вот мой SendLocalNotification метод. Я хотел бы, чтобы удаленные уведомления также запускали этот метод, чтобы они могли выглядеть одинаково.
void SendLocalNotification(string body)
{
//Unique request code to avoid PendingIntent collision.
var requestCode = new Random().Next();
// accept intent
var acceptIntent = new Intent(this, typeof(MainActivity));
acceptIntent.SetAction("ACCEPT_ACTION");
var pendingIntentAccept = PendingIntent.GetActivity(this, requestCode, acceptIntent, PendingIntentFlags.OneShot);
// decline intent
var declineIntent = new Intent(this, typeof(MainActivity));
declineIntent.SetAction("DECLINE_ACTION");
var pendingIntentDecline = PendingIntent.GetActivity(this, requestCode, declineIntent, PendingIntentFlags.OneShot);
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.SingleTop);
var notificationBuilder = new NotificationCompat.Builder(this)
.AddAction(0, "Accept", pendingIntentAccept)
.AddAction(0, "Decline", pendingIntentDecline)
.SetContentTitle("Content Title")
.SetSmallIcon(Resource.Drawable.laundry_basket_icon_15875)
.SetContentText("content text")
.SetContentInfo("content info")
.SetSubText("sub text")
.SetAutoCancel(true)
.SetShowWhen(true)
.SetContentIntent(pendingIntentAccept)
.SetContentIntent(pendingIntentDecline);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
notificationBuilder.SetChannelId(AppConstants.NotificationChannelName);
}
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
РЕДАКТИРОВАТЬ: Вот код, который я использую для отправки моего уведомления. У меня сложилось впечатление, что наличие тега data
означает, что отправляется уведомление о данных, которое затем принимается OnMessageReceived
.
public void SendNotificationByTag(string tag, string notificationBody = "", string notificationTitle = "")
{
var url = $"{_baseUrl}/messages/?api-version=2015-01";
var client = new RestClient($"{url}");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("ServiceBusNotification-Format", "gcm");
request.AddHeader("ServiceBusNotification-Tags", $"{tag}");
request.AddHeader("Authorization", $"{NotificationHelper.CreateSasToken(url, "DefaultFullSharedAccessSignature", $"{_configuration["DefaultFullSharedAccessSignature"]}")}");
request.AddParameter("application/json", $"{{\"data\":\n\t{{\n\t\t\"gcm.notification.body\":\"{notificationBody}\", \n\t\t\"gcm.notification.title\":\"{notificationTitle}\",\n\t}}\n}}", ParameterType.RequestBody);
client.Execute(request);
}
.