diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 9e65ff240..c394fde5b 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -8,6 +8,8 @@ + + + + + diff --git a/android/app/src/main/res/raw/keep.xml b/android/app/src/main/res/raw/keep.xml new file mode 100644 index 000000000..2a8d6c080 --- /dev/null +++ b/android/app/src/main/res/raw/keep.xml @@ -0,0 +1,4 @@ + + + diff --git a/lib/features/routines/notifications/workout_notification_service.dart b/lib/features/routines/notifications/workout_notification_service.dart index 2d0f7f7d5..074cc0949 100644 --- a/lib/features/routines/notifications/workout_notification_service.dart +++ b/lib/features/routines/notifications/workout_notification_service.dart @@ -69,6 +69,12 @@ abstract class WorkoutNotificationService { Future requestPermissions(WorkoutNotificationLabels labels); + /// Whether rest alarms fire on time. Without, Android may delay them. + Future canScheduleExactAlarms(); + + /// Sends the user to the system setting for exact alarms + Future requestExactAlarms(); + Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels); Future showControls(WorkoutControls controls, WorkoutNotificationLabels labels); @@ -94,6 +100,12 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService { @override Future requestPermissions(WorkoutNotificationLabels labels) async {} + @override + Future canScheduleExactAlarms() async => true; + + @override + Future requestExactAlarms() async {} + @override Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async {} @@ -130,7 +142,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { return _initialized ??= _plugin .initialize( settings: InitializationSettings( - android: const AndroidInitializationSettings('@mipmap/ic_launcher'), + android: const AndroidInitializationSettings('ic_stat_wger'), iOS: DarwinInitializationSettings( requestAlertPermission: false, requestBadgePermission: false, @@ -175,16 +187,31 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { _logger.fine('Notification permission granted: $granted'); } + AndroidFlutterLocalNotificationsPlugin? get _android => + _plugin.resolvePlatformSpecificImplementation(); + + @override + Future canScheduleExactAlarms() async => + await _android?.canScheduleExactNotifications() ?? true; + + @override + Future requestExactAlarms() async { + await _android?.requestExactAlarmsPermission(); + } + @override Future scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels) async { await _ensureInitialized(labels); + final exact = await canScheduleExactAlarms(); await _plugin.zonedSchedule( id: _notificationId, scheduledDate: tz.TZDateTime.from(alarm.at, tz.UTC), title: alarm.title, body: alarm.body, payload: alarm.payload.encode(), - androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, + androidScheduleMode: exact + ? AndroidScheduleMode.exactAllowWhileIdle + : AndroidScheduleMode.inexactAllowWhileIdle, notificationDetails: NotificationDetails( android: AndroidNotificationDetails( _alarmChannelId, @@ -270,6 +297,11 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService { } } +/// Whether rest alarms fire on time, rechecked whenever it is shown again +final exactAlarmsAllowedProvider = FutureProvider.autoDispose( + (ref) => ref.read(workoutNotificationServiceProvider).canScheduleExactAlarms(), +); + final workoutNotificationServiceProvider = Provider((ref) { if (!kIsWeb && (defaultTargetPlatform == TargetPlatform.android || diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index db541fc63..046ef90b0 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -22,6 +22,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/exercises/widgets/images.dart'; import 'package:wger/features/routines/models/day.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; @@ -55,6 +56,7 @@ class _GymModeOptionsState extends ConsumerState { Widget build(BuildContext context) { final gymState = ref.watch(gymStateProvider); final gymNotifier = ref.watch(gymStateProvider.notifier); + final isAndroid = !kIsWeb && defaultTargetPlatform == TargetPlatform.android; final i18n = AppLocalizations.of(context); // If the value in the provider changed, update the controller text @@ -176,8 +178,27 @@ class _GymModeOptionsState extends ConsumerState { ? (value) => gymNotifier.setRestAlarmEnabled(value) : null, ), + // Android delays alarms without the exact alarm permission + if (isAndroid && + gymState.showTimerPages && + gymState.restAlarmEnabled && + ref.watch(exactAlarmsAllowedProvider).value == false) + ListTile( + key: const ValueKey('gym-mode-exact-alarm-hint'), + leading: const Icon(Icons.alarm_off), + title: Text(i18n.gymModeExactAlarmMissing), + trailing: TextButton( + onPressed: () async { + await ref + .read(workoutNotificationServiceProvider) + .requestExactAlarms(); + ref.invalidate(exactAlarmsAllowedProvider); + }, + child: Text(i18n.gymModeExactAlarmAllow), + ), + ), // The ongoing notification only exists on Android - if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) + if (isAndroid) SwitchListTile( key: const ValueKey('gym-mode-workout-notification'), title: Text(i18n.gymModeWorkoutNotification), diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7c8418d6a..0c0d62230 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -379,6 +379,8 @@ "gymModeRestAlarm": "Rest alarm", "gymModeRestAlarmHelp": "System notification when the rest is over, also with the screen locked", "gymModeWorkoutNotification": "Workout notification", + "gymModeExactAlarmMissing": "Without the exact alarm permission, the rest alarm can be a few minutes late", + "gymModeExactAlarmAllow": "Allow", "gymModeWorkoutNotificationHelp": "Shows the rest and the next set, with buttons to log it or skip the rest", "workoutNotificationRestOver": "Rest is over", "workoutNotificationNext": "Next: {set}", diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index 7bf6d21b4..ba7369fa4 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -65,6 +65,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti ) as _i3.Future); + @override + _i3.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + @override _i3.Future scheduleRestAlarm( _i4.RestAlarm? alarm, diff --git a/test/features/routines/notifications/workout_notification_service_test.dart b/test/features/routines/notifications/workout_notification_service_test.dart new file mode 100644 index 000000000..5eb31deec --- /dev/null +++ b/test/features/routines/notifications/workout_notification_service_test.dart @@ -0,0 +1,111 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/services.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:timezone/data/latest.dart' as tzdata; +import 'package:wger/features/routines/notifications/workout_notification_content.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; + +void main() { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('dexterous.com/flutter/local_notifications'); + late List calls; + late bool exactAllowed; + + const labels = WorkoutNotificationLabels( + logSet: 'Log set', + skipRest: 'Skip rest', + controlsChannel: 'Workout', + alarmChannel: 'Rest alarm', + notLoggedTitle: 'Set not logged', + notLoggedBody: 'Open gym mode', + ); + final payload = WorkoutNotificationPayload( + routineId: 1, + dayId: 1, + iteration: 1, + workoutStart: DateTime.utc(2025, 3, 29, 14, 33), + ); + + setUpAll(tzdata.initializeTimeZones); + + setUp(() { + // The Android side of the plugin, talking to a fake platform channel + FlutterLocalNotificationsPlatform.instance = AndroidFlutterLocalNotificationsPlugin(); + calls = []; + exactAllowed = true; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return switch (call.method) { + 'canScheduleExactNotifications' => exactAllowed, + 'initialize' => true, + _ => null, + }; + }); + addTearDown(() => binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null)); + }); + + Map scheduled() => + (calls.singleWhere((c) => c.method == 'zonedSchedule').arguments as Map)['platformSpecifics'] + as Map; + + RestAlarm alarm({bool canLogSet = true}) => RestAlarm( + at: DateTime.now().add(const Duration(minutes: 2)), + title: 'Rest is over', + body: 'Next: Bench press', + canLogSet: canLogSet, + payload: payload, + ); + + test('Initializes with the monochrome status bar icon', () async { + await LocalWorkoutNotificationService().initialize(labels); + + final init = calls.singleWhere((c) => c.method == 'initialize').arguments as Map; + expect(init['defaultIcon'], 'ic_stat_wger'); + }); + + test('The rest alarm is exact when allowed', () async { + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(), labels); + + expect(scheduled()['scheduleMode'], AndroidScheduleMode.exactAllowWhileIdle.name); + }); + + test('Without the exact alarm permission it falls back to an inexact alarm', () async { + exactAllowed = false; + + await LocalWorkoutNotificationService().scheduleRestAlarm(alarm(), labels); + + expect(scheduled()['scheduleMode'], AndroidScheduleMode.inexactAllowWhileIdle.name); + }); + + test('The alarm only offers "Log set" when the set can be logged', () async { + final service = LocalWorkoutNotificationService(); + + await service.scheduleRestAlarm(alarm(), labels); + expect( + (scheduled()['actions'] as List).map((a) => (a as Map)['id']), + [WORKOUT_NOTIFICATION_ACTION_LOG_SET], + ); + + calls.clear(); + await service.scheduleRestAlarm(alarm(canLogSet: false), labels); + expect(scheduled()['actions'], anyOf(isNull, isEmpty)); + }); +} diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index 8142901c2..ba8bbf2db 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -657,6 +657,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot ) as _i10.Future); + @override + _i10.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i10.Future.value(false), + ) + as _i10.Future); + + @override + _i10.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i10.Future.value(), + returnValueForMissingStub: _i10.Future.value(), + ) + as _i10.Future); + @override _i10.Future scheduleRestAlarm( _i32.RestAlarm? alarm, diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index a290f0244..1e480bc6d 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -20,8 +20,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/features/routines/notifications/workout_notification_service.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/start_page.dart'; @@ -29,19 +32,27 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/l10n/localizations_delegates.dart'; import '../../../../../test_data/routines.dart'; +import 'start_page_test.mocks.dart'; +@GenerateMocks([WorkoutNotificationService]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); late ProviderContainer container; + late MockWorkoutNotificationService notificationService; setUp(() { // Use in-memory shared preferences to avoid platform channels during tests SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + notificationService = MockWorkoutNotificationService(); + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => true); + when(notificationService.requestExactAlarms()).thenAnswer((_) async {}); + container = ProviderContainer( overrides: [ gymStateProvider.overrideWith(() => GymStateNotifier()), + workoutNotificationServiceProvider.overrideWithValue(notificationService), ], ); @@ -248,4 +259,39 @@ void main() { expect(notifier.state.showDistinctLogs, isFalse); }); + + group('Exact alarm hint', () { + Future openOptions(WidgetTester tester) async { + await pumpGymModeOptions(tester); + await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile'))); + await tester.pumpAndSettle(); + } + + final hint = find.byKey(const ValueKey('gym-mode-exact-alarm-hint')); + + testWidgets('Shown without the permission, the button asks for it', (tester) async { + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + await openOptions(tester); + expect(hint, findsOneWidget); + + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => true); + await tester.ensureVisible(find.descendant(of: hint, matching: find.byType(TextButton))); + await tester.tap(find.descendant(of: hint, matching: find.byType(TextButton))); + await tester.pumpAndSettle(); + + verify(notificationService.requestExactAlarms()).called(1); + expect(hint, findsNothing, reason: 'rechecked after returning from the setting'); + }); + + testWidgets('Not shown with the permission or with the rest alarm off', (tester) async { + await openOptions(tester); + expect(hint, findsNothing); + + when(notificationService.canScheduleExactAlarms()).thenAnswer((_) async => false); + container.invalidate(exactAlarmsAllowedProvider); + container.read(gymStateProvider.notifier).setRestAlarmEnabled(false); + await tester.pumpAndSettle(); + expect(hint, findsNothing); + }); + }); } diff --git a/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart new file mode 100644 index 000000000..3b91bfbcd --- /dev/null +++ b/test/features/routines/widgets/gym_mode/start_page_test.mocks.dart @@ -0,0 +1,124 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/routines/widgets/gym_mode/start_page_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes + +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/notifications/workout_notification_content.dart' as _i4; +import 'package:wger/features/routines/notifications/workout_notification_service.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [WorkoutNotificationService]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNotificationService { + MockWorkoutNotificationService() { + _i1.throwOnMissingStub(this); + } + + @override + bool get supportsControls => + (super.noSuchMethod( + Invocation.getter(#supportsControls), + returnValue: false, + ) + as bool); + + @override + _i3.Future initialize( + _i4.WorkoutNotificationLabels? labels, { + _i2.WorkoutNotificationTapHandler? onTap, + }) => + (super.noSuchMethod( + Invocation.method(#initialize, [labels], {#onTap: onTap}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future requestPermissions(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#requestPermissions, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future canScheduleExactAlarms() => + (super.noSuchMethod( + Invocation.method(#canScheduleExactAlarms, []), + returnValue: _i3.Future.value(false), + ) + as _i3.Future); + + @override + _i3.Future requestExactAlarms() => + (super.noSuchMethod( + Invocation.method(#requestExactAlarms, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future scheduleRestAlarm( + _i4.RestAlarm? alarm, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#scheduleRestAlarm, [alarm, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future showControls( + _i4.WorkoutControls? controls, + _i4.WorkoutNotificationLabels? labels, + ) => + (super.noSuchMethod( + Invocation.method(#showControls, [controls, labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future showNotLogged(_i4.WorkoutNotificationLabels? labels) => + (super.noSuchMethod( + Invocation.method(#showNotLogged, [labels]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future cancelAll() => + (super.noSuchMethod( + Invocation.method(#cancelAll, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +}