didChangeAppLifecycleState method
Called when the system puts the app in the background or returns the app to the foreground.
An example of implementing this method is provided in the class-level documentation for the WidgetsBindingObserver class.
This method exposes notifications from SystemChannels.lifecycle.
See also:
- AppLifecycleListener, an alternative API for responding to application lifecycle changes.
Implementation
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Only capture paused — on iOS the hidden state fires before paused and
// would overwrite _pausedAtMs with a slightly later timestamp. detached
// means the engine is being torn down; the app will cold-start next time,
// which initialize() already handles, so capturing it here is a no-op.
if (state == AppLifecycleState.paused) {
_pausedAtMs = DateTime.now().millisecondsSinceEpoch;
} else if (state == AppLifecycleState.resumed && _initialized) {
final now = DateTime.now().millisecondsSinceEpoch;
if (_pausedAtMs != null && (now - _pausedAtMs!) > _debounceThresholdMs) {
if (!_isStartingSession) {
_isStartingSession = true;
pendingSessionFuture = () async {
try {
await _startNewSession();
} catch (e) {
debugPrint('[SessionService] Error starting new session: $e');
} finally {
_isStartingSession = false;
pendingSessionFuture = null;
}
}();
// Intentionally fire-and-forget — the observer callback is synchronous.
// `unawaited` documents this and suppresses the unawaited_futures lint.
unawaited(pendingSessionFuture!);
}
}
_pausedAtMs = null;
}
}