65 lines
2.5 KiB
C#

using System;
using Android.App;
using Android.Content;
using static System.Net.Mime.MediaTypeNames;
using Application = Android.App.Application;
namespace gehGassi.LocalNotifications.Platforms
{
[BroadcastReceiver]
public class ScheduledNotificationReceiver : BroadcastReceiver
{
public override async void OnReceive(Context context, Intent intent)
{
try
{
var notificationManager = NotificationManager.FromContext(Application.Context);
string notificationDetailsJson = intent.GetStringExtra(Constants.NOTIFICATION_REQUEST);
bool repeat = intent.GetBooleanExtra(Constants.REPEAT, false);
var notificationService = GetDefaultNotificationService();
if (string.IsNullOrEmpty(notificationDetailsJson))
{
Notification notification = (Notification)intent.GetParcelableExtra(Constants.NOTIFICATION);
notification.When = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
int notificationId = intent.GetIntExtra(Constants.NOTIFICATION_ID, 0);
if (!repeat)
await notificationService.RemoveNotificationFromCacheAsync(context, notificationId);
NotificationService.NotificationReceived(notificationId, string.Empty);
notificationManager.Notify(notificationId, notification);
}
else
{
NotificationRequest notificationRequest = notificationDetailsJson.JsonToObject<NotificationRequest>();
if (repeat)
{
notificationRequest.LastCalledAt = DateTime.Now;
await notificationService.SaveScheduledNotificationAsync(context, notificationRequest);
return;
}
else
{
//Console.WriteLine("Remove from cache | " + notificationRequest.Title);
await notificationService.RemoveNotificationFromCacheAsync(context, notificationRequest.NotificationId);
}
await notificationService.ShowNotificationAsync(context, notificationRequest);
}
return;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public NotificationService GetDefaultNotificationService() => new NotificationService();
}
}