Schedule exact rest alarms on Android and add a status bar icon

This commit is contained in:
Roland Geider
2026-10-25 11:28:45 +01:00
parent 5668ce985e
commit 6ce9f4bb0d
11 changed files with 390 additions and 3 deletions

View File

@@ -8,6 +8,8 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- Rest alarms on time; user-granted on Android 14+, inexact without it -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- Health Connect permissions for the imported measurement types. Must
list every type in enabledHealthMetrics: Health Connect cannot grant

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Status bar icon of the workout notifications (Material "fitness_center") -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M20.57,14.86L22,13.43 20.57,12 17,15.57 8.43,7 12,3.43 10.57,2 9.14,3.43 7.71,2 5.57,4.14 4.14,2.71 2.71,4.14l1.43,1.43L2,7.71l1.43,1.43L2,10.57 3.43,12 7,8.43 15.57,17 12,20.57 13.43,22l1.43,-1.43L16.29,22l2.14,-2.14 1.43,1.43 1.43,-1.43 -1.43,-1.43L22,16.29z" />
</vector>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Referenced by name from Dart only, the resource shrinker can't see that -->
<resources xmlns:tools="http://schemas.android.com/tools"
tools:keep="@drawable/ic_stat_wger" />

View File

@@ -69,6 +69,12 @@ abstract class WorkoutNotificationService {
Future<void> requestPermissions(WorkoutNotificationLabels labels);
/// Whether rest alarms fire on time. Without, Android may delay them.
Future<bool> canScheduleExactAlarms();
/// Sends the user to the system setting for exact alarms
Future<void> requestExactAlarms();
Future<void> scheduleRestAlarm(RestAlarm alarm, WorkoutNotificationLabels labels);
Future<void> showControls(WorkoutControls controls, WorkoutNotificationLabels labels);
@@ -94,6 +100,12 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService {
@override
Future<void> requestPermissions(WorkoutNotificationLabels labels) async {}
@override
Future<bool> canScheduleExactAlarms() async => true;
@override
Future<void> requestExactAlarms() async {}
@override
Future<void> 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<AndroidFlutterLocalNotificationsPlugin>();
@override
Future<bool> canScheduleExactAlarms() async =>
await _android?.canScheduleExactNotifications() ?? true;
@override
Future<void> requestExactAlarms() async {
await _android?.requestExactAlarmsPermission();
}
@override
Future<void> 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<bool>(
(ref) => ref.read(workoutNotificationServiceProvider).canScheduleExactAlarms(),
);
final workoutNotificationServiceProvider = Provider<WorkoutNotificationService>((ref) {
if (!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.android ||

View File

@@ -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<GymModeOptions> {
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<GymModeOptions> {
? (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),

View File

@@ -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}",

View File

@@ -65,6 +65,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti
)
as _i3.Future<void>);
@override
_i3.Future<bool> canScheduleExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#canScheduleExactAlarms, []),
returnValue: _i3.Future<bool>.value(false),
)
as _i3.Future<bool>);
@override
_i3.Future<void> requestExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#requestExactAlarms, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> scheduleRestAlarm(
_i4.RestAlarm? alarm,

View File

@@ -0,0 +1,111 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* 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 <http://www.gnu.org/licenses/>.
*/
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<MethodCall> 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<Object?, Object?> 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));
});
}

View File

@@ -657,6 +657,23 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot
)
as _i10.Future<void>);
@override
_i10.Future<bool> canScheduleExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#canScheduleExactAlarms, []),
returnValue: _i10.Future<bool>.value(false),
)
as _i10.Future<bool>);
@override
_i10.Future<void> requestExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#requestExactAlarms, []),
returnValue: _i10.Future<void>.value(),
returnValueForMissingStub: _i10.Future<void>.value(),
)
as _i10.Future<void>);
@override
_i10.Future<void> scheduleRestAlarm(
_i32.RestAlarm? alarm,

View File

@@ -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<void> 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);
});
});
}

View File

@@ -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<void> initialize(
_i4.WorkoutNotificationLabels? labels, {
_i2.WorkoutNotificationTapHandler? onTap,
}) =>
(super.noSuchMethod(
Invocation.method(#initialize, [labels], {#onTap: onTap}),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> requestPermissions(_i4.WorkoutNotificationLabels? labels) =>
(super.noSuchMethod(
Invocation.method(#requestPermissions, [labels]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<bool> canScheduleExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#canScheduleExactAlarms, []),
returnValue: _i3.Future<bool>.value(false),
)
as _i3.Future<bool>);
@override
_i3.Future<void> requestExactAlarms() =>
(super.noSuchMethod(
Invocation.method(#requestExactAlarms, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> scheduleRestAlarm(
_i4.RestAlarm? alarm,
_i4.WorkoutNotificationLabels? labels,
) =>
(super.noSuchMethod(
Invocation.method(#scheduleRestAlarm, [alarm, labels]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> showControls(
_i4.WorkoutControls? controls,
_i4.WorkoutNotificationLabels? labels,
) =>
(super.noSuchMethod(
Invocation.method(#showControls, [controls, labels]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> showNotLogged(_i4.WorkoutNotificationLabels? labels) =>
(super.noSuchMethod(
Invocation.method(#showNotLogged, [labels]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> cancelAll() =>
(super.noSuchMethod(
Invocation.method(#cancelAll, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}