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) {
  if (!_isRunning) return; // Only handle if service is running

  switch (state) {
    case AppLifecycleState.resumed:
      // ✅ App returned to foreground - resume monitoring
      if (_isPaused) {
        _resumeMonitoring();
      }
      break;

    case AppLifecycleState.inactive:
      // ✅ App is transitioning (e.g., system dialog, app switcher)
      if (autoPauseOnInactive) {
        _pauseMonitoring();
      }
      break;

    case AppLifecycleState.paused:
      // ✅ App in background - MUST pause to save battery
      if (autoPauseOnBackground) {
        _pauseMonitoring();
      }
      break;

    case AppLifecycleState.detached:
      // ✅ App is being destroyed - stop completely
      _pauseMonitoring();
      break;

    case AppLifecycleState.hidden:
      // ✅ App is hidden - pause monitoring
      if (autoPauseOnBackground) {
        _pauseMonitoring();
      }
      break;
  }
}