initialize method
Initializes the App Open Ad lifecycle manager and registers app state observer.
Implementation
Future<void> initialize() async {
if (_isInitialized) return;
if (!AdConstants.isPlatformSupported) return;
_isInitialized = true;
WidgetsBinding.instance.addObserver(this);
_coldStartDeadline = DateTime.now().add(coldStartTimeout);
try {
final prefs = await SharedPreferences.getInstance();
final launchCount = (prefs.getInt(_keyLaunchCount) ?? 0) + 1;
await prefs.setInt(_keyLaunchCount, launchCount);
developer.log('App Launch Count: $launchCount', name: 'AppOpenAdManager');
if (launchCount >= 2) {
// 2nd cold start or later: preload and show only if ready before deadline
loadAd(
onLoaded: () {
if (_coldStartDeadline != null &&
DateTime.now().isBefore(_coldStartDeadline!)) {
developer.log(
'Cold start ad ready within deadline. Presenting App Open Ad.',
name: 'AppOpenAdManager',
);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_isInitialized) {
showAdIfAvailable();
}
});
} else {
developer.log(
'Cold start ad loaded after deadline. Keeping cached for next resume.',
name: 'AppOpenAdManager',
);
}
},
);
} else {
// 1st launch: preload in background for future resumes without interrupting first impressions
loadAd();
}
} catch (e) {
developer.log('Error initializing AppOpenAdManager: $e',
name: 'AppOpenAdManager');
loadAd();
}
}