From ff297bf4b88fb7bcaefcdc26b7af23376db1307e Mon Sep 17 00:00:00 2001
From: Armand <4831c0@proton.me>
Date: Tue, 8 Sep 2026 15:26:55 +0200
Subject: [PATCH] feat(notifications): add multi-backend notification delivery
with FCM and AlarmManager fallback
- Add Google Play Services (GMS) availability check via MainActivity platform channel
- Add AlarmNotificationService using android_alarm_manager_plus for periodic background checks
- Add NotificationDeliveryService coordinator to resolve delivery method and sync backends
- Add NotificationDeliveryMethod setting (auto, fcm, alarm) with automatic fallback when GMS is unavailable
- Update en/hu localization strings for notification delivery method selection
- Add unit and integration tests for alarm scheduling, settings effects handoff, and e2e wakeup diffing
---
firka/android/app/build.gradle.kts | 3 +-
.../android/app/src/main/AndroidManifest.xml | 1 +
.../kotlin/app/firka/naplo/MainActivity.kt | 11 ++
firka/android/build.gradle.kts | 22 +--
firka/lib/api/login_finish.dart | 5 +-
firka/lib/app/initialization.dart | 10 +-
firka/lib/core/settings.dart | 6 +
firka/lib/core/settings/settings_effects.dart | 11 +-
firka/lib/core/settings/settings_schema.dart | 9 +
.../core/settings/settings_schema.gen.dart | 4 +-
firka/lib/l10n | 2 +-
.../services/alarm_notification_service.dart | 86 +++++++++
firka/lib/services/fcm_service.dart | 22 ++-
.../notification_delivery_service.dart | 150 +++++++++++++++
.../settings/settings_account_picker.dart | 9 +-
firka/pubspec.yaml | 1 +
firka/test/e2e/notification_diff_test.dart | 33 ++++
.../alarm_notification_service_test.dart | 102 ++++++++++
.../notification_delivery_service_test.dart | 174 ++++++++++++++++++
19 files changed, 626 insertions(+), 35 deletions(-)
create mode 100644 firka/lib/services/alarm_notification_service.dart
create mode 100644 firka/lib/services/notification_delivery_service.dart
create mode 100644 firka/test/services/alarm_notification_service_test.dart
create mode 100644 firka/test/services/notification_delivery_service_test.dart
diff --git a/firka/android/app/build.gradle.kts b/firka/android/app/build.gradle.kts
index 1a9034aa..b464c729 100644
--- a/firka/android/app/build.gradle.kts
+++ b/firka/android/app/build.gradle.kts
@@ -12,7 +12,7 @@ plugins {
}
android {
namespace = "app.firka.naplo"
- compileSdk = flutter.compileSdkVersion
+ compileSdk = 37
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
@@ -77,6 +77,7 @@ configurations.all {
dependencies {
implementation("androidx.glance:glance-appwidget:1.1.1")
implementation("com.google.android.gms:play-services-wearable:18.1.0")
+ implementation("com.google.android.gms:play-services-base:18.5.0")
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}
// Ensure .env exists before Flutter bundles assets (copy from .env.example if missing)
diff --git a/firka/android/app/src/main/AndroidManifest.xml b/firka/android/app/src/main/AndroidManifest.xml
index 25b8e773..75f21326 100644
--- a/firka/android/app/src/main/AndroidManifest.xml
+++ b/firka/android/app/src/main/AndroidManifest.xml
@@ -3,6 +3,7 @@
+
diff --git a/firka/android/app/src/main/kotlin/app/firka/naplo/MainActivity.kt b/firka/android/app/src/main/kotlin/app/firka/naplo/MainActivity.kt
index a1827455..e1e5f73e 100644
--- a/firka/android/app/src/main/kotlin/app/firka/naplo/MainActivity.kt
+++ b/firka/android/app/src/main/kotlin/app/firka/naplo/MainActivity.kt
@@ -10,6 +10,8 @@ import android.util.Log
import androidx.glance.appwidget.updateAll
import app.firka.naplo.glance.TimetableWidget
import app.firka.naplo.glance.TimetableWidgetReceiver
+import com.google.android.gms.common.ConnectionResult
+import com.google.android.gms.common.GoogleApiAvailability
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
@@ -174,6 +176,15 @@ class MainActivity : FlutterActivity() {
}
}
}
+ "isGmsAvailable" -> {
+ try {
+ val availability = GoogleApiAvailability.getInstance()
+ val resultCode = availability.isGooglePlayServicesAvailable(context)
+ result.success(resultCode == ConnectionResult.SUCCESS)
+ } catch (e: Exception) {
+ result.success(false)
+ }
+ }
else -> {
result.notImplemented()
}
diff --git a/firka/android/build.gradle.kts b/firka/android/build.gradle.kts
index 7f428e0c..e1985b7c 100644
--- a/firka/android/build.gradle.kts
+++ b/firka/android/build.gradle.kts
@@ -13,25 +13,19 @@ rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
+ project.layout.buildDirectory.value(newSubprojectBuildDir)
- afterEvaluate {
- if (plugins.hasPlugin("com.android.application")) {
- extensions.configure {
- compileSdk = 37
- defaultConfig {
- // buildToolsVersion can be set here if needed
+ if (project.name != "app") {
+ project.evaluationDependsOn(":app")
+
+ afterEvaluate {
+ if (plugins.hasPlugin("com.android.library")) {
+ extensions.configure {
+ compileSdk = 37
}
}
}
-
- if (plugins.hasPlugin("com.android.library")) {
- extensions.configure {
- compileSdk = 37
- }
- }
}
-
- project.layout.buildDirectory.value(newSubprojectBuildDir)
}
tasks.register("clean") {
diff --git a/firka/lib/api/login_finish.dart b/firka/lib/api/login_finish.dart
index ee264854..e758cd57 100644
--- a/firka/lib/api/login_finish.dart
+++ b/firka/lib/api/login_finish.dart
@@ -1,6 +1,6 @@
import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
-import "package:firka/services/fcm_service.dart";
+import "package:firka/services/notification_delivery_service.dart";
import "package:firka_common/data/models/token_model.dart";
import "package:kreta_api/kreta_api.dart";
@@ -18,9 +18,8 @@ Future completeLogin(
await initializeApp();
if (data.client != null) {
- await FcmService.onUserLogin(
+ await NotificationDeliveryService.onUserLogin(
client: data.client!,
- settingsStore: data.settings,
);
}
}
diff --git a/firka/lib/app/initialization.dart b/firka/lib/app/initialization.dart
index af794d7a..c418acff 100644
--- a/firka/lib/app/initialization.dart
+++ b/firka/lib/app/initialization.dart
@@ -8,7 +8,7 @@ import 'package:flutter/services.dart';
import 'package:firka/app/app_state.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka_common/data/models/token_model.dart';
-import 'package:firka/services/fcm_service.dart';
+import 'package:firka/services/notification_delivery_service.dart';
import 'package:firka/data/widget.dart';
import 'package:firka/core/settings/settings_effects.dart';
import 'package:firka/core/settings/settings_repository.dart';
@@ -167,7 +167,7 @@ Future _initData(AppInitialization init) async {
// this the FCM token would only ever get (re-)registered for a user who
// explicitly logs out and back in. Safe to call on every startup:
// onUserLogin() itself no-ops if notifyAll is off or permission is denied.
- unawaited(FcmService.onUserLogin(client: init.client!));
+ unawaited(NotificationDeliveryService.onUserLogin(client: init.client!));
// Immediately refresh widget state from cached Isar lessons so widget is up to date
unawaited(WidgetCacheHelper.updateWidgetCacheFromIsar());
@@ -248,11 +248,11 @@ Future initializeApp() async {
registerSettingsEffects(initData.settings, initData);
try {
- await FcmService.initialize().timeout(const Duration(seconds: 8));
+ await NotificationDeliveryService.initialize().timeout(const Duration(seconds: 8));
} on TimeoutException catch (e, st) {
- logger.warning('FcmService init timed out: $e', e, st);
+ logger.warning('NotificationDeliveryService init timed out: $e', e, st);
} catch (e, st) {
- logger.severe('Failed to initialize FcmService: $e', e, st);
+ logger.severe('Failed to initialize NotificationDeliveryService: $e', e, st);
}
await _initData(initData);
diff --git a/firka/lib/core/settings.dart b/firka/lib/core/settings.dart
index 99be6ef1..26ccfc79 100644
--- a/firka/lib/core/settings.dart
+++ b/firka/lib/core/settings.dart
@@ -293,6 +293,12 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsRegistry.notifyAll,
always,
),
+ SettingsUiHeaderSmall(l10n.s_notif_delivery_method_header, isPushNotificationsEnabled),
+ SettingsUiEnum(SettingsRegistry.notificationDeliveryMethod, [
+ l10n.s_notif_delivery_auto,
+ l10n.s_notif_delivery_fcm,
+ l10n.s_notif_delivery_alarm,
+ ], isPushNotificationsEnabled),
SettingsUiHeaderSmall(l10n.s_notif_wakeup_interval_header, isPushNotificationsEnabled),
SettingsUiEnum(SettingsRegistry.notifyWakeupInterval, [
l10n.s_notif_wakeup_hourly,
diff --git a/firka/lib/core/settings/settings_effects.dart b/firka/lib/core/settings/settings_effects.dart
index 16831969..51950f3c 100644
--- a/firka/lib/core/settings/settings_effects.dart
+++ b/firka/lib/core/settings/settings_effects.dart
@@ -5,6 +5,7 @@ import "package:permission_handler/permission_handler.dart";
import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
import "package:firka/services/fcm_service.dart";
+import "package:firka/services/notification_delivery_service.dart";
import "package:firka/services/watch_sync_helper.dart";
import "settings_repository.dart";
@@ -53,12 +54,16 @@ void registerSettingsEffects(
}
});
- repo.onChange(SettingsRegistry.notifyAll, (enabled) async {
- await FcmService.handleEnabledChange(enabled);
+ repo.onChange(SettingsRegistry.notifyAll, (_) async {
+ await NotificationDeliveryService.syncDeliveryBackend();
+ });
+
+ repo.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
+ await NotificationDeliveryService.syncDeliveryBackend();
});
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
- await FcmService.handleWakeupIntervalChange();
+ await NotificationDeliveryService.handleWakeupIntervalChange();
});
for (final setting in [
diff --git a/firka/lib/core/settings/settings_schema.dart b/firka/lib/core/settings/settings_schema.dart
index b89b4b21..fe755d6a 100644
--- a/firka/lib/core/settings/settings_schema.dart
+++ b/firka/lib/core/settings/settings_schema.dart
@@ -24,6 +24,8 @@ enum TitleCapitalization { lower, normal, upper }
/// `wakeup-2hourly` sent by the `fcm-notifier` backend service.
enum NotifyWakeupInterval { hourly, twoHourly }
+enum NotificationDeliveryMethod { auto, fcm, alarm }
+
abstract class SettingsSchema {
@DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120)
double get bellDelay;
@@ -177,4 +179,11 @@ abstract class SettingsSchema {
@BoolSetting(id: 1046, defaultValue: false)
bool get fcmDebugNotifyOnMessage;
+
+ @EnumSetting(
+ id: 1047,
+ defaultValue: NotificationDeliveryMethod.auto,
+ values: NotificationDeliveryMethod.values,
+ )
+ NotificationDeliveryMethod get notificationDeliveryMethod;
}
diff --git a/firka/lib/core/settings/settings_schema.gen.dart b/firka/lib/core/settings/settings_schema.gen.dart
index c06c15e2..d2e97b61 100644
--- a/firka/lib/core/settings/settings_schema.gen.dart
+++ b/firka/lib/core/settings/settings_schema.gen.dart
@@ -44,9 +44,10 @@ class SettingsRegistry {
static const notifyMutedSubjects = StringSetting(id: 1044, defaultValue: "[]");
static const notifyWakeupInterval = EnumSetting(id: 1045, defaultValue: NotifyWakeupInterval.hourly, values: NotifyWakeupInterval.values);
static const fcmDebugNotifyOnMessage = BoolSetting(id: 1046, defaultValue: false);
+ static const notificationDeliveryMethod = EnumSetting(id: 1047, defaultValue: NotificationDeliveryMethod.auto, values: NotificationDeliveryMethod.values);
static const all = [
- bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage,
+ bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod,
];
}
@@ -92,4 +93,5 @@ extension SettingsAccessors on SettingsRepository {
SilentlySettable get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
SilentlySettable get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
SilentlySettable get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
+ SilentlySettable get notificationDeliveryMethod => SilentlySettable(this, SettingsRegistry.notificationDeliveryMethod);
}
diff --git a/firka/lib/l10n b/firka/lib/l10n
index b80df466..d0641965 160000
--- a/firka/lib/l10n
+++ b/firka/lib/l10n
@@ -1 +1 @@
-Subproject commit b80df466d249e5541bfaa990b3c77ef16719cd42
+Subproject commit d064196553e5365f7dc1bb880c80f5ba84996ea5
diff --git a/firka/lib/services/alarm_notification_service.dart b/firka/lib/services/alarm_notification_service.dart
new file mode 100644
index 00000000..0857c2ab
--- /dev/null
+++ b/firka/lib/services/alarm_notification_service.dart
@@ -0,0 +1,86 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
+import 'package:flutter/widgets.dart';
+import 'package:logging/logging.dart';
+
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/services/notification_diff_service.dart';
+
+const int _alarmNotificationSyncId = 910001;
+
+@pragma('vm:entry-point')
+Future alarmNotificationWakeupCallback() async {
+ WidgetsFlutterBinding.ensureInitialized();
+ await NotificationDiffService.checkAll();
+}
+
+class AlarmNotificationService {
+ static final Logger _logger = Logger('AlarmNotificationService');
+ static bool _isInitialized = false;
+
+ @visibleForTesting
+ static bool? isAndroidOverride;
+
+ static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
+
+ @visibleForTesting
+ static void resetForTesting() {
+ _isInitialized = false;
+ isAndroidOverride = null;
+ }
+
+ static bool get isInitialized => _isInitialized;
+
+ static Future initialize() async {
+ if (_isInitialized || !_isAndroid) return;
+ try {
+ await AndroidAlarmManager.initialize();
+ _isInitialized = true;
+ _logger.info('AlarmNotificationService initialized');
+ } catch (e, st) {
+ _logger.severe('Failed to initialize AlarmNotificationService: $e', e, st);
+ }
+ }
+
+ static Duration _durationFor(NotifyWakeupInterval interval) {
+ switch (interval) {
+ case NotifyWakeupInterval.hourly:
+ return const Duration(hours: 1);
+ case NotifyWakeupInterval.twoHourly:
+ return const Duration(hours: 2);
+ }
+ }
+
+ static Future schedule() async {
+ if (!_isAndroid) return;
+ try {
+ await initialize();
+ final interval = _durationFor(Settings.notifyWakeupInterval.value);
+ await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
+ await AndroidAlarmManager.periodic(
+ interval,
+ _alarmNotificationSyncId,
+ alarmNotificationWakeupCallback,
+ exact: false,
+ wakeup: true,
+ rescheduleOnReboot: true,
+ );
+ _logger.info('Scheduled periodic alarm every ${interval.inHours}h');
+ } catch (e, st) {
+ _logger.severe('Failed to schedule alarm: $e', e, st);
+ }
+ }
+
+ static Future cancel() async {
+ if (!_isAndroid) return;
+ try {
+ await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
+ _logger.info('Cancelled periodic alarm');
+ } catch (e, st) {
+ _logger.warning('Failed to cancel alarm: $e', e, st);
+ }
+ }
+}
diff --git a/firka/lib/services/fcm_service.dart b/firka/lib/services/fcm_service.dart
index 859c6b2f..8e12413c 100644
--- a/firka/lib/services/fcm_service.dart
+++ b/firka/lib/services/fcm_service.dart
@@ -151,11 +151,29 @@ class FcmService {
}
}
+ static Future? _pendingPermissionRequest;
+
static Future _requestPermission() async {
+ if (_pendingPermissionRequest != null) {
+ return await _pendingPermissionRequest!;
+ }
final status = await Permission.notification.status;
if (status.isGranted) return true;
- final result = await Permission.notification.request();
- return result.isGranted;
+
+ final future = () async {
+ try {
+ final result = await Permission.notification.request();
+ return result.isGranted;
+ } catch (e) {
+ _logger.warning('Failed to request notification permission: $e');
+ return false;
+ } finally {
+ _pendingPermissionRequest = null;
+ }
+ }();
+
+ _pendingPermissionRequest = future;
+ return await future;
}
static String? _currentStudentId(KretaClient? client) {
diff --git a/firka/lib/services/notification_delivery_service.dart b/firka/lib/services/notification_delivery_service.dart
new file mode 100644
index 00000000..a71a39a4
--- /dev/null
+++ b/firka/lib/services/notification_delivery_service.dart
@@ -0,0 +1,150 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:logging/logging.dart';
+
+import 'package:firka/api/client/kreta_client.dart';
+import 'package:firka_common/data/database.dart';
+import 'package:firka_common/data/models/token_model.dart';
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/services/alarm_notification_service.dart';
+import 'package:firka/services/fcm_service.dart';
+
+class NotificationDeliveryService {
+ static final Logger _logger = Logger('NotificationDeliveryService');
+ static const MethodChannel _mainChannel = MethodChannel('firka.app/main');
+
+ static bool? _cachedGmsAvailable;
+
+ @visibleForTesting
+ static bool? gmsAvailabilityOverride;
+
+ @visibleForTesting
+ static bool? isAndroidOverride;
+
+ static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
+
+ @visibleForTesting
+ static void resetForTesting() {
+ _cachedGmsAvailable = null;
+ gmsAvailabilityOverride = null;
+ isAndroidOverride = null;
+ }
+
+ static Future isGmsAvailable({bool forceRefresh = false}) async {
+ if (gmsAvailabilityOverride != null) {
+ return gmsAvailabilityOverride!;
+ }
+ if (!_isAndroid) return false;
+ if (_cachedGmsAvailable != null && !forceRefresh) {
+ return _cachedGmsAvailable!;
+ }
+ try {
+ final available = await _mainChannel.invokeMethod('isGmsAvailable');
+ _cachedGmsAvailable = available ?? false;
+ return _cachedGmsAvailable!;
+ } catch (e) {
+ _logger.warning('Error checking GMS availability: $e');
+ _cachedGmsAvailable = false;
+ return false;
+ }
+ }
+
+ static Future getEffectiveMethod() async {
+ final configured = Settings.notificationDeliveryMethod.value;
+ if (configured != NotificationDeliveryMethod.auto) {
+ return configured;
+ }
+ final gms = await isGmsAvailable();
+ return gms ? NotificationDeliveryMethod.fcm : NotificationDeliveryMethod.alarm;
+ }
+
+ static Future initialize() async {
+ if (!_isAndroid) return;
+
+ final gms = await isGmsAvailable();
+ _logger.info('Initializing NotificationDeliveryService (GMS available: $gms)');
+
+ await AlarmNotificationService.initialize();
+
+ if (gms) {
+ await FcmService.initialize();
+ }
+
+ await syncDeliveryBackend();
+ }
+
+ static Future syncDeliveryBackend() async {
+ if (!_isAndroid) return;
+
+ try {
+ if (!Settings.notifyAll.value) {
+ _logger.info('Push notifications disabled, tearing down delivery backends');
+ await FcmService.handleEnabledChange(false);
+ await AlarmNotificationService.cancel();
+ return;
+ }
+
+ final effectiveMethod = await getEffectiveMethod();
+ _logger.info('Syncing delivery backend for effective method: $effectiveMethod');
+
+ switch (effectiveMethod) {
+ case NotificationDeliveryMethod.fcm:
+ await AlarmNotificationService.cancel();
+ await FcmService.handleEnabledChange(true);
+ break;
+ case NotificationDeliveryMethod.alarm:
+ await FcmService.handleEnabledChange(false);
+ await AlarmNotificationService.schedule();
+ break;
+ case NotificationDeliveryMethod.auto:
+ break;
+ }
+ } catch (e, st) {
+ _logger.warning('Failed to sync delivery backend: $e', e, st);
+ }
+ }
+
+ static Future handleWakeupIntervalChange() async {
+ if (!Settings.notifyAll.value) return;
+
+ final effectiveMethod = await getEffectiveMethod();
+ if (effectiveMethod == NotificationDeliveryMethod.fcm) {
+ await FcmService.handleWakeupIntervalChange();
+ } else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
+ await AlarmNotificationService.schedule();
+ }
+ }
+
+ static Future onUserLogin({required KretaClient client}) async {
+ if (!_isAndroid) return;
+
+ try {
+ final effectiveMethod = await getEffectiveMethod();
+ if (effectiveMethod == NotificationDeliveryMethod.fcm) {
+ await FcmService.onUserLogin(client: client);
+ } else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
+ await AlarmNotificationService.schedule();
+ }
+ } catch (e, st) {
+ _logger.warning('Failed to process onUserLogin: $e', e, st);
+ }
+ }
+
+ static Future onUserLogout() async {
+ if (!_isAndroid) return;
+
+ final effectiveMethod = await getEffectiveMethod();
+ if (effectiveMethod == NotificationDeliveryMethod.fcm) {
+ await FcmService.onUserLogout();
+ } else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
+ final tokenCount = await isarInit.tokenModels.count();
+ if (tokenCount == 0) {
+ await AlarmNotificationService.cancel();
+ }
+ }
+ }
+}
diff --git a/firka/lib/ui/phone/screens/settings/settings_account_picker.dart b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart
index b3626e9b..356c0251 100644
--- a/firka/lib/ui/phone/screens/settings/settings_account_picker.dart
+++ b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart
@@ -1,7 +1,7 @@
import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart";
import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
-import "package:firka/services/fcm_service.dart";
+import "package:firka/services/notification_delivery_service.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka/ui/phone/widgets/login_webview.dart";
@@ -137,15 +137,14 @@ class SettingsAccountPickerView extends StatelessWidget {
return;
}
- await FcmService.onUserLogout();
+ await NotificationDeliveryService.onUserLogout();
await data.settings.setSelectedAccountKey(token.key);
await initializeApp();
if (data.client != null) {
- await FcmService.onUserLogin(
+ await NotificationDeliveryService.onUserLogin(
client: data.client!,
- settingsStore: data.settings,
);
}
@@ -157,7 +156,7 @@ class SettingsAccountPickerView extends StatelessWidget {
Future _logout(BuildContext context) async {
try {
- await FcmService.onUserLogout();
+ await NotificationDeliveryService.onUserLogout();
final active = data.client!.cache.token.key;
diff --git a/firka/pubspec.yaml b/firka/pubspec.yaml
index 3889a4ae..65527594 100644
--- a/firka/pubspec.yaml
+++ b/firka/pubspec.yaml
@@ -20,6 +20,7 @@ dependencies:
firebase_core: ^4.1.1
firebase_messaging: ^16.0.2
flutter_local_notifications: ^18.0.1
+ android_alarm_manager_plus: ^5.1.1
dio: ^5.8.0+1
isar_community: 3.3.0
isar_community_flutter_libs: 3.3.0
diff --git a/firka/test/e2e/notification_diff_test.dart b/firka/test/e2e/notification_diff_test.dart
index 0c524c4c..b484f9e2 100644
--- a/firka/test/e2e/notification_diff_test.dart
+++ b/firka/test/e2e/notification_diff_test.dart
@@ -6,6 +6,7 @@ import 'package:firka/app/app_state.dart';
import 'package:firka/app/initialization.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka/services/local_notification_service.dart';
import 'package:firka/services/notification_diff_service.dart';
import 'package:firka_common/data/database.dart';
@@ -312,6 +313,38 @@ void main() {
.where((n) => n.body.contains('Fizika') || n.body.contains('Newton'))
.toList();
expect(fizikaNotifs, isEmpty);
+
+ LocalNotificationService.postedNotifications.clear();
+ final alarmGradeUid = 'test-grade-alarm-${DateTime.now().millisecondsSinceEpoch}';
+ final alarmGradeTime = DateTime.now().toUtc().toIso8601String();
+ await _postItem(httpClient, '/admin/api/grades', {
+ 'Uid': alarmGradeUid,
+ 'RogzitesDatuma': alarmGradeTime,
+ 'KeszitesDatuma': alarmGradeTime,
+ 'Tantargy': {
+ 'Uid': '14,TOR',
+ 'Nev': 'Történelem',
+ 'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
+ 'SortIndex': 14,
+ },
+ 'Tema': 'Középkor',
+ 'Tipus': {'Uid': '1', 'Nev': 'Szóbeli'},
+ 'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
+ 'ErtekeloTanarNeve': 'Hérodotosz',
+ 'Jelleg': 'Ertekeles',
+ 'SzamErtek': 5,
+ 'SzovegesErtek': 'Jeles',
+ 'SulySzazalekErteke': 100,
+ 'OsztalyCsoport': {'Uid': '10,11.A'},
+ });
+
+ await alarmNotificationWakeupCallback();
+
+ final alarmNotif = LocalNotificationService.postedNotifications.firstWhere(
+ (n) => n.title.contains('jegy') && n.body.contains('Történelem'),
+ );
+ expect(alarmNotif.title, contains('jegy'));
+ expect(alarmNotif.body, contains('Történelem'));
});
});
});
diff --git a/firka/test/services/alarm_notification_service_test.dart b/firka/test/services/alarm_notification_service_test.dart
new file mode 100644
index 00000000..8c1c109c
--- /dev/null
+++ b/firka/test/services/alarm_notification_service_test.dart
@@ -0,0 +1,102 @@
+import 'dart:io';
+import 'dart:ui';
+
+import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/services/alarm_notification_service.dart';
+import 'package:firka_common/data/database.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const alarmChannel = MethodChannel(
+ 'dev.fluttercommunity.plus/android_alarm_manager',
+ JSONMethodCodec(),
+ );
+
+ late Directory tempDir;
+ late List alarmCalls;
+
+ setUp(() async {
+ alarmCalls = [];
+ AlarmNotificationService.resetForTesting();
+ AlarmNotificationService.isAndroidOverride = true;
+
+ tempDir = Directory.systemTemp.createTempSync('alarm_test_');
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ const MethodChannel('plugins.flutter.io/path_provider'),
+ (MethodCall methodCall) async => tempDir.path,
+ );
+
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ alarmChannel,
+ (MethodCall call) async {
+ alarmCalls.add(call);
+ return true;
+ },
+ );
+
+ AndroidAlarmManager.setTestOverrides(
+ getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
+ );
+
+ final isar = await initDB();
+ await isar.writeTxn(() async {
+ await isar.clear();
+ });
+ Settings = SettingsRepository(isar);
+ await Settings.loadAll();
+ });
+
+ tearDown(() async {
+ AlarmNotificationService.resetForTesting();
+ try {
+ tempDir.deleteSync(recursive: true);
+ } catch (_) {}
+ });
+
+ test('initialize invokes AlarmService.start', () async {
+ await AlarmNotificationService.initialize();
+ expect(AlarmNotificationService.isInitialized, isTrue);
+ expect(alarmCalls.any((call) => call.method == 'AlarmService.start'), isTrue);
+ });
+
+ test('schedule sets up hourly periodic alarm with sync ID 910001', () async {
+ await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
+ await AlarmNotificationService.schedule();
+
+ final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
+ expect(periodicCalls, isNotEmpty);
+ final call = periodicCalls.last;
+ expect(call.arguments[0], 910001);
+ expect(call.arguments[3], isTrue); // wakeup
+ expect(call.arguments[5], const Duration(hours: 1).inMilliseconds);
+ expect(call.arguments[6], isTrue); // rescheduleOnReboot
+ });
+
+ test('schedule sets up two-hourly periodic alarm when configured', () async {
+ await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
+ await AlarmNotificationService.schedule();
+
+ final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
+ expect(periodicCalls, isNotEmpty);
+ final call = periodicCalls.last;
+ expect(call.arguments[0], 910001);
+ expect(call.arguments[3], isTrue); // wakeup
+ expect(call.arguments[5], const Duration(hours: 2).inMilliseconds);
+ expect(call.arguments[6], isTrue); // rescheduleOnReboot
+ });
+
+ test('cancel invokes Alarm.cancel with sync ID 910001', () async {
+ await AlarmNotificationService.cancel();
+
+ final cancelCalls = alarmCalls.where((call) => call.method == 'Alarm.cancel').toList();
+ expect(cancelCalls, isNotEmpty);
+ expect(cancelCalls.last.arguments[0], 910001);
+ });
+}
diff --git a/firka/test/services/notification_delivery_service_test.dart b/firka/test/services/notification_delivery_service_test.dart
new file mode 100644
index 00000000..35393b1c
--- /dev/null
+++ b/firka/test/services/notification_delivery_service_test.dart
@@ -0,0 +1,174 @@
+import 'dart:io';
+import 'dart:ui';
+
+import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
+import 'package:firka/core/settings/settings_repository.dart';
+import 'package:firka/core/settings/settings_schema.dart';
+import 'package:firka/services/alarm_notification_service.dart';
+import 'package:firka/services/notification_delivery_service.dart';
+import 'package:firka_common/data/database.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const alarmChannel = MethodChannel(
+ 'dev.fluttercommunity.plus/android_alarm_manager',
+ JSONMethodCodec(),
+ );
+
+ late Directory tempDir;
+ late List alarmCalls;
+
+ setUp(() async {
+ alarmCalls = [];
+ NotificationDeliveryService.resetForTesting();
+ AlarmNotificationService.resetForTesting();
+ NotificationDeliveryService.isAndroidOverride = true;
+ AlarmNotificationService.isAndroidOverride = true;
+
+ tempDir = Directory.systemTemp.createTempSync('delivery_test_');
+
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ const MethodChannel('plugins.flutter.io/path_provider'),
+ (MethodCall methodCall) async => tempDir.path,
+ );
+
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ alarmChannel,
+ (MethodCall call) async {
+ alarmCalls.add(call);
+ return true;
+ },
+ );
+
+ AndroidAlarmManager.setTestOverrides(
+ getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
+ );
+
+ final isar = await initDB();
+ await isar.writeTxn(() async {
+ await isar.clear();
+ });
+ Settings = SettingsRepository(isar);
+ await Settings.loadAll();
+ });
+
+ tearDown(() async {
+ NotificationDeliveryService.resetForTesting();
+ AlarmNotificationService.resetForTesting();
+ try {
+ tempDir.deleteSync(recursive: true);
+ } catch (_) {}
+ });
+
+ group('NotificationDeliveryService effective method resolution', () {
+ test('resolves explicit FCM setting', () async {
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
+ final effective = await NotificationDeliveryService.getEffectiveMethod();
+ expect(effective, NotificationDeliveryMethod.fcm);
+ });
+
+ test('resolves explicit Alarm setting', () async {
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ final effective = await NotificationDeliveryService.getEffectiveMethod();
+ expect(effective, NotificationDeliveryMethod.alarm);
+ });
+
+ test('auto resolves to FCM when GMS is available', () async {
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
+ NotificationDeliveryService.gmsAvailabilityOverride = true;
+
+ final effective = await NotificationDeliveryService.getEffectiveMethod();
+ expect(effective, NotificationDeliveryMethod.fcm);
+ });
+
+ test('auto resolves to Alarm when GMS is unavailable', () async {
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
+ NotificationDeliveryService.gmsAvailabilityOverride = false;
+
+ final effective = await NotificationDeliveryService.getEffectiveMethod();
+ expect(effective, NotificationDeliveryMethod.alarm);
+ });
+ });
+
+ group('NotificationDeliveryService backend coordination & settings effects', () {
+ test('syncDeliveryBackend cancels alarm when notifyAll is disabled', () async {
+ await Settings.notifyAll.set(false);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+
+ alarmCalls.clear();
+ await NotificationDeliveryService.syncDeliveryBackend();
+
+ final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
+ expect(cancelCalls, isNotEmpty);
+ expect(cancelCalls.last.arguments[0], 910001);
+ });
+
+ test('syncDeliveryBackend schedules alarm when method is alarm and notifyAll is true', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
+
+ alarmCalls.clear();
+ await NotificationDeliveryService.syncDeliveryBackend();
+
+ final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
+ expect(periodicCalls, isNotEmpty);
+ expect(periodicCalls.last.arguments[0], 910001);
+ expect(periodicCalls.last.arguments[5], const Duration(hours: 1).inMilliseconds);
+ });
+
+ test('syncDeliveryBackend cancels alarm when switching from alarm to fcm', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ await NotificationDeliveryService.syncDeliveryBackend();
+
+ alarmCalls.clear();
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
+ await NotificationDeliveryService.syncDeliveryBackend();
+
+ final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
+ expect(cancelCalls, isNotEmpty);
+ expect(cancelCalls.last.arguments[0], 910001);
+ });
+
+ test('handleWakeupIntervalChange reschedules alarm with new duration', () async {
+ await Settings.notifyAll.set(true);
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
+
+ alarmCalls.clear();
+ await NotificationDeliveryService.handleWakeupIntervalChange();
+
+ final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
+ expect(periodicCalls, isNotEmpty);
+ expect(periodicCalls.last.arguments[5], const Duration(hours: 2).inMilliseconds);
+ });
+
+ test('changing settings triggers registered settings effects', () async {
+ Settings.onChange(SettingsRegistry.notifyAll, (_) async {
+ await NotificationDeliveryService.syncDeliveryBackend();
+ });
+ Settings.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
+ await NotificationDeliveryService.syncDeliveryBackend();
+ });
+ Settings.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
+ await NotificationDeliveryService.handleWakeupIntervalChange();
+ });
+
+ await Settings.notifyAll.set(true);
+ alarmCalls.clear();
+
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
+ expect(alarmCalls.any((c) => c.method == 'Alarm.periodic'), isTrue);
+
+ alarmCalls.clear();
+ await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
+ expect(alarmCalls.any((c) => c.method == 'Alarm.cancel'), isTrue);
+ });
+ });
+}