End the iOS background task once a notification action is handled

This commit is contained in:
Roland Geider
2026-10-25 11:48:04 +01:00
parent 6ce9f4bb0d
commit 3312a0a334
8 changed files with 145 additions and 14 deletions

View File

@@ -50,6 +50,47 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin {
}
}
/// Keeps the app running while the main isolate handles a notification
/// action, until Dart reports it as handled
private final class NotificationActionTasks: NSObject, FlutterPlugin {
static let pluginName = "NotificationActionTasks"
private static let channelName = "de.wger.flutter/notification_actions"
/// Upper bound if Dart never reports back, e.g. without a running workout
private static let timeout: TimeInterval = 20
private static var tasks: [UIBackgroundTaskIdentifier] = []
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(NotificationActionTasks(), channel: channel)
}
static func begin() {
var task: UIBackgroundTaskIdentifier = .invalid
task = UIApplication.shared.beginBackgroundTask { end(task) }
tasks.append(task)
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { end(task) }
}
private static func end(_ task: UIBackgroundTaskIdentifier) {
guard let index = tasks.firstIndex(of: task) else {
return
}
tasks.remove(at: index)
UIApplication.shared.endBackgroundTask(task)
}
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard call.method == "actionHandled" else {
result(FlutterMethodNotImplemented)
return
}
for task in Self.tasks {
Self.end(task)
}
result(nil)
}
}
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
override func application(
@@ -62,24 +103,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin {
}
// A notification action is handled by the main isolate, but the plugin
// completes the response right away and iOS suspends the app again.
// Keep it running briefly so the action is processed now.
// completes the response right away and iOS suspends the app again
override func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
var task: UIBackgroundTaskIdentifier = .invalid
task = UIApplication.shared.beginBackgroundTask {
UIApplication.shared.endBackgroundTask(task)
task = .invalid
}
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
if task != .invalid {
UIApplication.shared.endBackgroundTask(task)
task = .invalid
}
}
NotificationActionTasks.begin()
super.userNotificationCenter(
center, didReceive: response, withCompletionHandler: completionHandler)
}
@@ -90,6 +120,13 @@ private final class StorageExclusionPlugin: NSObject, FlutterPlugin {
GeneratedPluginRegistrant.register(with: registry)
}
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
if let registrar = engineBridge.pluginRegistry.registrar(
forPlugin: NotificationActionTasks.pluginName
) {
NotificationActionTasks.register(with: registrar)
} else {
NSLog("NotificationActionTasks registrar unavailable")
}
guard
let registrar = engineBridge.pluginRegistry.registrar(
forPlugin: StorageExclusionPlugin.pluginName

View File

@@ -127,6 +127,16 @@ class WorkoutNotificationController {
/// Carries out a notification action. Stale actions only refresh the
/// notification, without a running session the user is sent to the app.
Future<void> handleAction(String? actionId, String? encodedPayload) async {
try {
await _handleAction(actionId, encodedPayload);
} finally {
// Lets iOS suspend the app again once the notification is up to date
await _queue;
await _service.actionHandled();
}
}
Future<void> _handleAction(String? actionId, String? encodedPayload) async {
final state = _ref.read(gymStateProvider);
if (!state.isInitialized) {
// E.g. iOS started the app in the background just for this action

View File

@@ -19,6 +19,7 @@
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -84,6 +85,9 @@ abstract class WorkoutNotificationService {
/// Removes the shown notification and a pending rest alarm
Future<void> cancelAll();
/// Lets the platform suspend the app again after an action
Future<void> actionHandled();
}
/// For platforms without workout notifications
@@ -117,6 +121,9 @@ class NoopWorkoutNotificationService implements WorkoutNotificationService {
@override
Future<void> cancelAll() async {}
@override
Future<void> actionHandled() async {}
}
/// Android and iOS, via flutter_local_notifications
@@ -125,6 +132,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService {
static const _controlsChannelId = 'workout_controls';
static const _alarmChannelId = 'rest_alarm';
static const _restEndCategory = 'workout_rest_end';
static const _actionTasksChannel = MethodChannel('de.wger.flutter/notification_actions');
final _logger = Logger('LocalWorkoutNotificationService');
final _plugin = FlutterLocalNotificationsPlugin();
@@ -226,6 +234,7 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService {
],
),
iOS: DarwinNotificationDetails(
presentSound: true,
categoryIdentifier: alarm.canLogSet ? _restEndCategory : null,
),
),
@@ -295,6 +304,19 @@ class LocalWorkoutNotificationService implements WorkoutNotificationService {
await _initialized;
await _plugin.cancel(id: _notificationId);
}
@override
Future<void> actionHandled() async {
// Only iOS holds the app awake for an action, see AppDelegate.swift
if (defaultTargetPlatform != TargetPlatform.iOS) {
return;
}
try {
await _actionTasksChannel.invokeMethod<void>('actionHandled');
} on PlatformException catch (e) {
_logger.warning('Could not end the background task: $e');
}
}
}
/// Whether rest alarms fire on time, rechecked whenever it is shown again

View File

@@ -56,6 +56,7 @@ void main() {
when(service.scheduleRestAlarm(any, any)).thenAnswer((_) async {});
when(service.showControls(any, any)).thenAnswer((_) async {});
when(service.showNotLogged(any)).thenAnswer((_) async {});
when(service.actionHandled()).thenAnswer((_) async {});
when(service.initialize(any, onTap: anyNamed('onTap'))).thenAnswer((_) async {});
logRepo = MockWorkoutLogRepository();
when(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {});
@@ -232,6 +233,8 @@ void main() {
verify(logRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1);
expect(gymState.state.currentPage, rest + 2);
// Only once the notification shows the new rest may iOS suspend the app
verifyInOrder([service.showControls(any, any), service.actionHandled()]);
final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured;
expect((alarms.last as RestAlarm).payload.restSlotUuid, slotPage(rest + 2).uuid);
});
@@ -284,7 +287,7 @@ void main() {
.handleAction(WORKOUT_NOTIFICATION_ACTION_LOG_SET, null);
await settle();
verify(service.showNotLogged(any)).called(1);
verifyInOrder([service.showNotLogged(any), service.actionHandled()]);
verifyNever(logRepo.addLocalDrift(any, dayId: anyNamed('dayId')));
});
});

View File

@@ -123,6 +123,15 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> actionHandled() =>
(super.noSuchMethod(
Invocation.method(#actionHandled, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}
/// A class which mocks [WorkoutLogRepository].

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -46,6 +47,37 @@ void main() {
setUpAll(tzdata.initializeTimeZones);
group('actionHandled', () {
const tasksChannel = MethodChannel('de.wger.flutter/notification_actions');
late List<String> taskCalls;
setUp(() {
taskCalls = [];
binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, (call) async {
taskCalls.add(call.method);
return null;
});
addTearDown(
() => binding.defaultBinaryMessenger.setMockMethodCallHandler(tasksChannel, null),
);
});
test('Ends the background task on iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
await LocalWorkoutNotificationService().actionHandled();
expect(taskCalls, ['actionHandled']);
});
test('Does nothing on Android, which keeps no task', () async {
await LocalWorkoutNotificationService().actionHandled();
expect(taskCalls, isEmpty);
});
});
setUp(() {
// The Android side of the plugin, talking to a fake platform channel
FlutterLocalNotificationsPlatform.instance = AndroidFlutterLocalNotificationsPlugin();

View File

@@ -715,4 +715,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i31.WorkoutNot
returnValueForMissingStub: _i10.Future<void>.value(),
)
as _i10.Future<void>);
@override
_i10.Future<void> actionHandled() =>
(super.noSuchMethod(
Invocation.method(#actionHandled, []),
returnValue: _i10.Future<void>.value(),
returnValueForMissingStub: _i10.Future<void>.value(),
)
as _i10.Future<void>);
}

View File

@@ -121,4 +121,13 @@ class MockWorkoutNotificationService extends _i1.Mock implements _i2.WorkoutNoti
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> actionHandled() =>
(super.noSuchMethod(
Invocation.method(#actionHandled, []),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}