7b824b6f0c
- Layout und Kalender angepasst - Push status meldung angepasst für Android
323 lines
12 KiB
C#
323 lines
12 KiB
C#
using Android.App;
|
|
using Android.Content;
|
|
using AndroidX.Core.App;
|
|
using cfs_tracker.Data;
|
|
using cfs_tracker.Helpers;
|
|
using cfs_tracker.Models;
|
|
using cfs_tracker.Services;
|
|
using Microsoft.Maui.ApplicationModel;
|
|
|
|
namespace cfs_tracker.Platforms.Android;
|
|
|
|
public sealed class AndroidNotificationScheduler : INotificationScheduler
|
|
{
|
|
private const string ChannelId = "cfs_tracker_reminders";
|
|
private const string ChannelName = "Erinnerungen";
|
|
private const string ChannelDescription = "Wie geht es dir? Erinnerungen";
|
|
private const string PrefScheduledIds = "notification_schedule_ids";
|
|
|
|
private const string PrefYellowLabel = "notification_label_yellow";
|
|
private const string PrefRedLabel = "notification_label_red";
|
|
private const string PrefGrayLabel = "notification_label_gray";
|
|
|
|
public const string ActionShowNotification = "cfs_tracker.action.SHOW_NOTIFICATION";
|
|
public const string ActionSaveStatus = "cfs_tracker.action.SAVE_STATUS";
|
|
public const string ActionOpenQuickEntry = "cfs_tracker.action.OPEN_QUICK_ENTRY";
|
|
|
|
public const string ExtraScheduleId = "schedule_id";
|
|
public const string ExtraDayOfWeek = "day_of_week";
|
|
public const string ExtraHour = "hour";
|
|
public const string ExtraMinute = "minute";
|
|
|
|
public const string ExtraRoute = "route";
|
|
public const string ExtraDate = "date";
|
|
public const string ExtraStatus = "status";
|
|
public const string ExtraCommit = "commit";
|
|
public const string ExtraNotificationId = "notification_id";
|
|
|
|
private readonly NotificationScheduleRepository _notificationScheduleRepository;
|
|
private readonly AppearanceService _appearanceService;
|
|
|
|
public AndroidNotificationScheduler(
|
|
NotificationScheduleRepository notificationScheduleRepository,
|
|
AppearanceService appearanceService)
|
|
{
|
|
_notificationScheduleRepository = notificationScheduleRepository;
|
|
_appearanceService = appearanceService;
|
|
}
|
|
|
|
public async Task<bool> EnsurePermissionAsync()
|
|
{
|
|
var status = await Permissions.CheckStatusAsync<NotificationPermission>();
|
|
if (status == PermissionStatus.Granted)
|
|
return true;
|
|
|
|
status = await Permissions.RequestAsync<NotificationPermission>();
|
|
return status == PermissionStatus.Granted;
|
|
}
|
|
|
|
public async Task SyncAsync()
|
|
{
|
|
var context = Platform.AppContext;
|
|
EnsureChannel(context);
|
|
|
|
CancelAllScheduled(context);
|
|
|
|
var granted = await EnsurePermissionAsync();
|
|
if (!granted)
|
|
return;
|
|
|
|
SaveActionLabelsToPreferences();
|
|
|
|
var schedules = await _notificationScheduleRepository.GetAllAsync();
|
|
var requestKeys = new List<string>();
|
|
|
|
foreach (var item in schedules.Where(x => x.IsEnabled && x.WeekdayMask != 0))
|
|
{
|
|
foreach (var day in GetScheduledDays(item.WeekdayMask))
|
|
{
|
|
ScheduleNextAlarm(context, item.Id, day, item.Hour, item.Minute);
|
|
requestKeys.Add($"{item.Id}:{(int)day}");
|
|
}
|
|
}
|
|
|
|
Preferences.Default.Set(PrefScheduledIds, string.Join(",", requestKeys));
|
|
}
|
|
|
|
private void SaveActionLabelsToPreferences()
|
|
{
|
|
Preferences.Default.Set(
|
|
PrefYellowLabel,
|
|
_appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"));
|
|
|
|
Preferences.Default.Set(
|
|
PrefRedLabel,
|
|
_appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"));
|
|
|
|
Preferences.Default.Set(
|
|
PrefGrayLabel,
|
|
_appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"));
|
|
}
|
|
|
|
internal static void ScheduleNextAlarm(
|
|
Context context,
|
|
int scheduleId,
|
|
DayOfWeek dayOfWeek,
|
|
int hour,
|
|
int minute)
|
|
{
|
|
var triggerAt = ComputeNextOccurrence(dayOfWeek, hour, minute);
|
|
var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService);
|
|
if (alarmManager is null)
|
|
return;
|
|
|
|
var intent = new Intent(context, typeof(CfsNotificationReceiver));
|
|
intent.SetAction(ActionShowNotification);
|
|
intent.PutExtra(ExtraScheduleId, scheduleId);
|
|
intent.PutExtra(ExtraDayOfWeek, (int)dayOfWeek);
|
|
intent.PutExtra(ExtraHour, hour);
|
|
intent.PutExtra(ExtraMinute, minute);
|
|
|
|
var requestCode = BuildAlarmRequestCode(scheduleId, dayOfWeek);
|
|
|
|
var pendingIntent = PendingIntent.GetBroadcast(
|
|
context,
|
|
requestCode,
|
|
intent,
|
|
BuildPendingIntentFlags());
|
|
|
|
var when = triggerAt.ToUnixTimeMilliseconds();
|
|
|
|
if (OperatingSystem.IsAndroidVersionAtLeast(23))
|
|
alarmManager.SetAndAllowWhileIdle(AlarmType.RtcWakeup, when, pendingIntent);
|
|
else
|
|
alarmManager.Set(AlarmType.RtcWakeup, when, pendingIntent);
|
|
}
|
|
|
|
internal static void ShowNotification(
|
|
Context context,
|
|
int scheduleId,
|
|
DayOfWeek dayOfWeek,
|
|
string title,
|
|
string message)
|
|
{
|
|
EnsureChannel(context);
|
|
|
|
var today = DateTime.Today;
|
|
var todayText = today.ToString("yyyy-MM-dd");
|
|
var notificationId = BuildNotificationId(scheduleId, dayOfWeek);
|
|
|
|
var openPendingIntent = CreateOpenQuickEntryPendingIntent(context, notificationId, todayText);
|
|
var yellowPendingIntent = CreateSaveStatusPendingIntent(context, notificationId, "yellow", todayText);
|
|
var redPendingIntent = CreateSaveStatusPendingIntent(context, notificationId, "red", todayText);
|
|
var grayPendingIntent = CreateSaveStatusPendingIntent(context, notificationId, "gray", todayText);
|
|
|
|
var yellowLabel = Preferences.Default.Get(PrefYellowLabel, "Gelb");
|
|
var redLabel = Preferences.Default.Get(PrefRedLabel, "Rot");
|
|
var grayLabel = Preferences.Default.Get(PrefGrayLabel, "Schwarz");
|
|
|
|
var smallIcon = context.ApplicationInfo?.Icon ?? global::Android.Resource.Drawable.IcDialogInfo;
|
|
|
|
var builder = new NotificationCompat.Builder(context, ChannelId)
|
|
.SetSmallIcon(smallIcon)
|
|
.SetContentTitle(title)
|
|
.SetContentText(message)
|
|
.SetPriority((int)NotificationPriority.High)
|
|
.SetAutoCancel(true)
|
|
.SetContentIntent(openPendingIntent)
|
|
.SetOnlyAlertOnce(true)
|
|
.AddAction(0, yellowLabel, yellowPendingIntent)
|
|
.AddAction(0, redLabel, redPendingIntent)
|
|
.AddAction(0, grayLabel, grayPendingIntent);
|
|
|
|
NotificationManagerCompat.From(context).Notify(notificationId, builder.Build());
|
|
}
|
|
|
|
private static PendingIntent CreateOpenQuickEntryPendingIntent(Context context, int notificationId, string date)
|
|
{
|
|
var launchIntent = context.PackageManager?.GetLaunchIntentForPackage(context.PackageName)
|
|
?? new Intent(context, typeof(MainActivity));
|
|
|
|
launchIntent.SetAction(ActionOpenQuickEntry);
|
|
launchIntent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop | ActivityFlags.NewTask);
|
|
launchIntent.PutExtra(ExtraRoute, "quickentry");
|
|
launchIntent.PutExtra(ExtraDate, date);
|
|
launchIntent.PutExtra(ExtraNotificationId, notificationId);
|
|
|
|
return PendingIntent.GetActivity(
|
|
context,
|
|
100000 + notificationId,
|
|
launchIntent,
|
|
BuildPendingIntentFlags());
|
|
}
|
|
|
|
private static PendingIntent CreateSaveStatusPendingIntent(Context context, int notificationId, string status, string date)
|
|
{
|
|
var intent = new Intent(context, typeof(CfsNotificationReceiver));
|
|
intent.SetAction(ActionSaveStatus);
|
|
intent.PutExtra(ExtraStatus, status);
|
|
intent.PutExtra(ExtraDate, date);
|
|
intent.PutExtra(ExtraNotificationId, notificationId);
|
|
|
|
return PendingIntent.GetBroadcast(
|
|
context,
|
|
BuildActionRequestCode(notificationId, status),
|
|
intent,
|
|
BuildPendingIntentFlags());
|
|
}
|
|
|
|
internal static void EnsureChannel(Context context)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
return;
|
|
|
|
var manager = (NotificationManager?)context.GetSystemService(Context.NotificationService);
|
|
if (manager is null)
|
|
return;
|
|
|
|
var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.Default)
|
|
{
|
|
Description = ChannelDescription
|
|
};
|
|
|
|
manager.CreateNotificationChannel(channel);
|
|
}
|
|
|
|
private void CancelAllScheduled(Context context)
|
|
{
|
|
var stored = Preferences.Default.Get(PrefScheduledIds, string.Empty);
|
|
if (string.IsNullOrWhiteSpace(stored))
|
|
return;
|
|
|
|
var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService);
|
|
if (alarmManager is null)
|
|
return;
|
|
|
|
foreach (var raw in stored.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
|
{
|
|
var parts = raw.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
if (parts.Length != 2)
|
|
continue;
|
|
|
|
if (!int.TryParse(parts[0], out var scheduleId))
|
|
continue;
|
|
|
|
if (!int.TryParse(parts[1], out var dayValue))
|
|
continue;
|
|
|
|
var day = (DayOfWeek)dayValue;
|
|
var requestCode = BuildAlarmRequestCode(scheduleId, day);
|
|
|
|
var intent = new Intent(context, typeof(CfsNotificationReceiver));
|
|
intent.SetAction(ActionShowNotification);
|
|
|
|
var pendingIntent = PendingIntent.GetBroadcast(
|
|
context,
|
|
requestCode,
|
|
intent,
|
|
BuildPendingIntentFlags());
|
|
|
|
alarmManager.Cancel(pendingIntent);
|
|
NotificationManagerCompat.From(context).Cancel(BuildNotificationId(scheduleId, day));
|
|
}
|
|
|
|
Preferences.Default.Remove(PrefScheduledIds);
|
|
}
|
|
|
|
private static PendingIntentFlags BuildPendingIntentFlags()
|
|
{
|
|
var flags = PendingIntentFlags.UpdateCurrent;
|
|
if (OperatingSystem.IsAndroidVersionAtLeast(23))
|
|
flags |= PendingIntentFlags.Immutable;
|
|
|
|
return flags;
|
|
}
|
|
|
|
private static DateTimeOffset ComputeNextOccurrence(DayOfWeek targetDay, int hour, int minute)
|
|
{
|
|
var now = DateTimeOffset.Now;
|
|
var todayAtTime = new DateTimeOffset(now.Year, now.Month, now.Day, hour, minute, 0, now.Offset);
|
|
|
|
var days = ((int)targetDay - (int)now.DayOfWeek + 7) % 7;
|
|
var target = todayAtTime.AddDays(days);
|
|
|
|
if (target <= now)
|
|
target = target.AddDays(7);
|
|
|
|
return target;
|
|
}
|
|
|
|
private static int BuildAlarmRequestCode(int scheduleId, DayOfWeek day)
|
|
{
|
|
return scheduleId * 10 + (int)day;
|
|
}
|
|
|
|
private static int BuildNotificationId(int scheduleId, DayOfWeek day)
|
|
{
|
|
return 500000 + scheduleId * 10 + (int)day;
|
|
}
|
|
|
|
private static int BuildActionRequestCode(int notificationId, string status)
|
|
{
|
|
return status switch
|
|
{
|
|
"yellow" => 600000 + notificationId * 10 + 1,
|
|
"red" => 600000 + notificationId * 10 + 2,
|
|
"gray" => 600000 + notificationId * 10 + 3,
|
|
_ => 600000 + notificationId * 10
|
|
};
|
|
}
|
|
|
|
private static IEnumerable<DayOfWeek> GetScheduledDays(int mask)
|
|
{
|
|
var flags = (NotificationWeekdays)mask;
|
|
|
|
if (flags.HasFlag(NotificationWeekdays.Monday)) yield return DayOfWeek.Monday;
|
|
if (flags.HasFlag(NotificationWeekdays.Tuesday)) yield return DayOfWeek.Tuesday;
|
|
if (flags.HasFlag(NotificationWeekdays.Wednesday)) yield return DayOfWeek.Wednesday;
|
|
if (flags.HasFlag(NotificationWeekdays.Thursday)) yield return DayOfWeek.Thursday;
|
|
if (flags.HasFlag(NotificationWeekdays.Friday)) yield return DayOfWeek.Friday;
|
|
if (flags.HasFlag(NotificationWeekdays.Saturday)) yield return DayOfWeek.Saturday;
|
|
if (flags.HasFlag(NotificationWeekdays.Sunday)) yield return DayOfWeek.Sunday;
|
|
}
|
|
} |