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 (!AdConstants.isPlatformSupported ||
      !AdsManager.isAdsEnabled ||
      !_isInitialized) {
    return;
  }

  if (state == AppLifecycleState.paused) {
    _backgroundTime = DateTime.now();
  } else if (state == AppLifecycleState.resumed) {
    if (_backgroundTime == null) return;
    final elapsed = DateTime.now().difference(_backgroundTime!);
    _backgroundTime = null;

    // AdMob Policy Guard: Only show if app remained in background >= backgroundThreshold (15s)
    if (elapsed >= backgroundThreshold) {
      developer.log(
        'App resumed after ${elapsed.inSeconds}s in background. Attempting App Open Ad.',
        name: 'AppOpenAdManager',
      );
      showAdIfAvailable();
    } else {
      developer.log(
        'App resumed after only ${elapsed.inSeconds}s. App Open Ad skipped to prevent user fatigue.',
        name: 'AppOpenAdManager',
      );
    }
  }
}