525 lines
19 KiB
C#
525 lines
19 KiB
C#
using Android.App;
|
|
using Android.Content;
|
|
using Android.Provider;
|
|
using AndroidX.Core.App;
|
|
using cfs_tracker.Data;
|
|
using cfs_tracker.Helpers;
|
|
using cfs_tracker.Models;
|
|
using cfs_tracker.Services;
|
|
using Microsoft.Maui.ApplicationModel;
|
|
using Microsoft.Maui.Storage;
|
|
|
|
namespace cfs_tracker.Platforms.Android;
|
|
|
|
public sealed class AndroidNotificationScheduler : INotificationScheduler
|
|
{
|
|
private const string ChannelIdSilent = "cfs_tracker_reminders_silent";
|
|
private const string ChannelIdVibrate = "cfs_tracker_reminders_vibrate";
|
|
private const string ChannelNameSilent = "Erinnerungen";
|
|
private const string ChannelNameVibrate = "Erinnerungen mit Vibration";
|
|
private const string ChannelDescription = "Wie geht es dir? Erinnerungen";
|
|
private const string PrefScheduledIds = "notification_schedule_ids";
|
|
private const string PrefVibrationEnabled = "notification_vibration_enabled";
|
|
|
|
private const string PrefYellowLabel = "notification_label_yellow";
|
|
private const string PrefRedLabel = "notification_label_red";
|
|
private const string PrefGrayLabel = "notification_label_gray";
|
|
|
|
private static readonly long[] NotificationVibrationPattern = new long[] { 0, 250, 150, 250 };
|
|
|
|
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 context = Platform.AppContext;
|
|
EnsureChannels(context);
|
|
|
|
var notificationStatus = await Permissions.CheckStatusAsync<NotificationPermission>();
|
|
if (notificationStatus != PermissionStatus.Granted)
|
|
{
|
|
notificationStatus = await Permissions.RequestAsync<NotificationPermission>();
|
|
if (notificationStatus != PermissionStatus.Granted)
|
|
return false;
|
|
}
|
|
|
|
if (!AreNotificationsEnabled(context))
|
|
{
|
|
OpenAppNotificationSettings(context);
|
|
return false;
|
|
}
|
|
|
|
var channelId = GetSelectedChannelId();
|
|
if (!IsNotificationChannelEnabled(context, channelId))
|
|
{
|
|
OpenNotificationChannelSettings(context, channelId);
|
|
return false;
|
|
}
|
|
|
|
if (CanScheduleExactAlarms(context))
|
|
return true;
|
|
|
|
OpenExactAlarmSettings(context);
|
|
return false;
|
|
}
|
|
|
|
public Task<bool> GetVibrationEnabledAsync() =>
|
|
Task.FromResult(Preferences.Default.Get(PrefVibrationEnabled, false));
|
|
|
|
public Task SetVibrationEnabledAsync(bool isEnabled)
|
|
{
|
|
Preferences.Default.Set(PrefVibrationEnabled, isEnabled);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public async Task SyncAsync()
|
|
{
|
|
var context = Platform.AppContext;
|
|
EnsureChannels(context);
|
|
|
|
CancelAllScheduled(context);
|
|
|
|
if (!await HasRequiredPermissionsAsync(context))
|
|
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());
|
|
if (pendingIntent is null)
|
|
return;
|
|
|
|
var when = triggerAt.ToUnixTimeMilliseconds();
|
|
|
|
if (OperatingSystem.IsAndroidVersionAtLeast(23) && CanUseExactAlarms(alarmManager))
|
|
{
|
|
alarmManager.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, when, pendingIntent);
|
|
return;
|
|
}
|
|
|
|
if (OperatingSystem.IsAndroidVersionAtLeast(23))
|
|
{
|
|
alarmManager.SetAndAllowWhileIdle(AlarmType.RtcWakeup, when, pendingIntent);
|
|
return;
|
|
}
|
|
|
|
alarmManager.Set(AlarmType.RtcWakeup, when, pendingIntent);
|
|
}
|
|
|
|
internal static void ShowNotification(
|
|
Context context,
|
|
int scheduleId,
|
|
DayOfWeek dayOfWeek,
|
|
string title,
|
|
string message)
|
|
{
|
|
EnsureChannels(context);
|
|
|
|
var vibrationEnabled = Preferences.Default.Get(PrefVibrationEnabled, false);
|
|
var channelId = GetChannelId(vibrationEnabled);
|
|
|
|
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");
|
|
|
|
// A dedicated monochrome status icon is more reliable for Android system surfaces,
|
|
// including mirrored smartwatch notifications, than the adaptive launcher icon.
|
|
var smallIcon = global::Android.Resource.Drawable.IcDialogInfo;
|
|
|
|
var builder = new NotificationCompat.Builder(context, channelId);
|
|
builder.SetSmallIcon(smallIcon);
|
|
builder.SetContentTitle(title);
|
|
builder.SetContentText(message);
|
|
builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(message));
|
|
builder.SetCategory(NotificationCompat.CategoryReminder);
|
|
builder.SetVisibility((int)NotificationCompat.VisibilityPublic);
|
|
builder.SetPriority((int)NotificationPriority.High);
|
|
builder.SetAutoCancel(true);
|
|
|
|
if (openPendingIntent is not null)
|
|
builder.SetContentIntent(openPendingIntent);
|
|
|
|
if (yellowPendingIntent is not null)
|
|
builder.AddAction(0, yellowLabel, yellowPendingIntent);
|
|
|
|
if (redPendingIntent is not null)
|
|
builder.AddAction(0, redLabel, redPendingIntent);
|
|
|
|
if (grayPendingIntent is not null)
|
|
builder.AddAction(0, grayLabel, grayPendingIntent);
|
|
|
|
if (vibrationEnabled && !OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
builder.SetVibrate(NotificationVibrationPattern);
|
|
|
|
var notification = builder.Build();
|
|
if (notification is null)
|
|
return;
|
|
|
|
var notificationManager = NotificationManagerCompat.From(context);
|
|
notificationManager?.Notify(notificationId, notification);
|
|
}
|
|
|
|
private static PendingIntent? CreateOpenQuickEntryPendingIntent(Context context, int notificationId, string date)
|
|
{
|
|
Intent launchIntent;
|
|
var packageName = context.PackageName;
|
|
if (!string.IsNullOrWhiteSpace(packageName))
|
|
{
|
|
launchIntent = context.PackageManager?.GetLaunchIntentForPackage(packageName)
|
|
?? new Intent(context, typeof(MainActivity));
|
|
}
|
|
else
|
|
{
|
|
launchIntent = 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 EnsureChannels(Context context)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
return;
|
|
|
|
var manager = (NotificationManager?)context.GetSystemService(Context.NotificationService);
|
|
if (manager is null)
|
|
return;
|
|
|
|
var silentChannel = new NotificationChannel(ChannelIdSilent, ChannelNameSilent, NotificationImportance.Default)
|
|
{
|
|
Description = ChannelDescription
|
|
};
|
|
silentChannel.EnableVibration(false);
|
|
manager.CreateNotificationChannel(silentChannel);
|
|
|
|
var vibrationChannel = new NotificationChannel(ChannelIdVibrate, ChannelNameVibrate, NotificationImportance.Default)
|
|
{
|
|
Description = ChannelDescription
|
|
};
|
|
vibrationChannel.EnableVibration(true);
|
|
vibrationChannel.SetVibrationPattern(NotificationVibrationPattern);
|
|
manager.CreateNotificationChannel(vibrationChannel);
|
|
}
|
|
|
|
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());
|
|
|
|
if (pendingIntent is not null)
|
|
alarmManager.Cancel(pendingIntent);
|
|
|
|
var notificationManager = NotificationManagerCompat.From(context);
|
|
notificationManager?.Cancel(BuildNotificationId(scheduleId, day));
|
|
}
|
|
|
|
Preferences.Default.Remove(PrefScheduledIds);
|
|
}
|
|
|
|
private static bool CanUseExactAlarms(AlarmManager alarmManager)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(31))
|
|
return true;
|
|
|
|
return alarmManager.CanScheduleExactAlarms();
|
|
}
|
|
|
|
private static async Task<bool> HasRequiredPermissionsAsync(Context context)
|
|
{
|
|
var notificationStatus = await Permissions.CheckStatusAsync<NotificationPermission>();
|
|
if (notificationStatus != PermissionStatus.Granted)
|
|
return false;
|
|
|
|
if (!AreNotificationsEnabled(context))
|
|
return false;
|
|
|
|
var channelId = GetSelectedChannelId();
|
|
if (!IsNotificationChannelEnabled(context, channelId))
|
|
return false;
|
|
|
|
return CanScheduleExactAlarms(context);
|
|
}
|
|
|
|
private static bool AreNotificationsEnabled(Context context)
|
|
{
|
|
var notificationManager = NotificationManagerCompat.From(context);
|
|
return notificationManager?.AreNotificationsEnabled() ?? false;
|
|
}
|
|
|
|
private static bool IsNotificationChannelEnabled(Context context, string channelId)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
return true;
|
|
|
|
var manager = (NotificationManager?)context.GetSystemService(Context.NotificationService);
|
|
if (manager is null)
|
|
return true;
|
|
|
|
var channel = manager.GetNotificationChannel(channelId);
|
|
return channel is null || channel.Importance != NotificationImportance.None;
|
|
}
|
|
|
|
private static bool CanScheduleExactAlarms(Context context)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(31))
|
|
return true;
|
|
|
|
var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService);
|
|
return alarmManager is null || alarmManager.CanScheduleExactAlarms();
|
|
}
|
|
|
|
private static void OpenAppNotificationSettings(Context context)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
{
|
|
OpenAppDetailsSettings(context);
|
|
return;
|
|
}
|
|
|
|
var intent = new Intent(Settings.ActionAppNotificationSettings);
|
|
intent.PutExtra(Settings.ExtraAppPackage, context.PackageName);
|
|
intent.AddFlags(ActivityFlags.NewTask);
|
|
context.StartActivity(intent);
|
|
}
|
|
|
|
private static void OpenNotificationChannelSettings(Context context, string channelId)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(26))
|
|
{
|
|
OpenAppNotificationSettings(context);
|
|
return;
|
|
}
|
|
|
|
var intent = new Intent(Settings.ActionChannelNotificationSettings);
|
|
intent.PutExtra(Settings.ExtraAppPackage, context.PackageName);
|
|
intent.PutExtra(Settings.ExtraChannelId, channelId);
|
|
intent.AddFlags(ActivityFlags.NewTask);
|
|
context.StartActivity(intent);
|
|
}
|
|
|
|
private static void OpenExactAlarmSettings(Context context)
|
|
{
|
|
if (!OperatingSystem.IsAndroidVersionAtLeast(31))
|
|
{
|
|
OpenAppDetailsSettings(context);
|
|
return;
|
|
}
|
|
|
|
var intent = new Intent(Settings.ActionRequestScheduleExactAlarm);
|
|
intent.SetData(global::Android.Net.Uri.Parse($"package:{context.PackageName}"));
|
|
intent.AddFlags(ActivityFlags.NewTask);
|
|
context.StartActivity(intent);
|
|
}
|
|
|
|
private static void OpenAppDetailsSettings(Context context)
|
|
{
|
|
var intent = new Intent(Settings.ActionApplicationDetailsSettings);
|
|
intent.SetData(global::Android.Net.Uri.Parse($"package:{context.PackageName}"));
|
|
intent.AddFlags(ActivityFlags.NewTask);
|
|
context.StartActivity(intent);
|
|
}
|
|
|
|
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 string GetChannelId(bool vibrationEnabled) =>
|
|
vibrationEnabled ? ChannelIdVibrate : ChannelIdSilent;
|
|
|
|
private static string GetSelectedChannelId() =>
|
|
GetChannelId(Preferences.Default.Get(PrefVibrationEnabled, false));
|
|
|
|
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;
|
|
}
|
|
}
|