didChangeAppLifecycleState method

  1. @override
void didChangeAppLifecycleState(
  1. AppLifecycleState state
)
override

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:

Implementation

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  final timestamp = DateTime.now().toIso8601String();
  String currentScreen = 'Unknown';

  if (_activeScreens.isNotEmpty) {
    _currentTracker = _activeScreens.values.last;
    currentScreen = _currentTracker?.screenName ?? 'Unknown';
  }

  switch (state) {
    case AppLifecycleState.resumed:
      developer.log('App moved to foreground at $timestamp on $currentScreen');

      if (_currentTracker != null && _currentTracker!.endTime != null) {
        final newTracker = ScreenTimeTracker(
          screenName: _currentTracker!.screenName,
          startTime: DateTime.now(),
          deviceInfo: _currentTracker!.deviceInfo,
          sessionId: sessionId,
        );
        _activeScreens[_activeScreens.keys.last] = newTracker;

        WidgetsBinding.instance.addPostFrameCallback((_) {
          final renderDuration = DateTime.now().difference(newTracker.startTime);
          newTracker.setRenderTime(renderDuration);
          developer.log('Tracking:::: ${newTracker.toString()}');
        });
      }
      break;

    case AppLifecycleState.paused:
      developer.log('App moved to background at $timestamp on $currentScreen');

      if (_currentTracker != null && _currentTracker!.endTime == null) {
        _currentTracker?.setEndTime(DateTime.now());
        developer.log('Tracking:::: ${_currentTracker.toString()}');
        _sendTracker(_currentTracker!);
      }
      break;

    case AppLifecycleState.inactive:
    case AppLifecycleState.detached:
      break;

    case AppLifecycleState.hidden:
      break;
  }
}