### Install Dependencies for Example App Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md Navigate to the google_mobile_ads package directory and run `flutter pub get` to install its dependencies before running the example app. ```bash cd packages/google_mobile_ads flutter pub get ``` -------------------------------- ### Run the Example App Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md Execute the example application for the google_mobile_ads package by navigating to its directory and running `flutter run`. ```bash cd packages/google_mobile_ads/example flutter run ``` -------------------------------- ### Run Analyzer and Formatter Checks Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md Before committing, run local checks for code analysis and formatting. Ensure `flutter_plugin_tools` and `clang-format` are installed. ```bash # Run the analyze check dart analyze ``` ```bash # Format code. # Requires `flutter_plugin_tools` (`pub global activate flutter_plugin_tools`). # Requires `clang-format` (can be installed via Brew on macOS). dart pub global run flutter_plugin_tools format ``` -------------------------------- ### AppOpenAdManager Class Structure Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Defines the basic structure for the AppOpenAdManager class, including the ad unit ID and variables to manage the loaded ad and its display state. This is the initial setup for managing app open ads. ```dart import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'dart:io' show Platform; class AppOpenAdManager { String adUnitId = ''; AppOpenAd? _appOpenAd; bool _isShowingAd = false; /// Load an [AppOpenAd]. void loadAd() { // We will implement this below. } /// Whether an ad is available to be shown. bool get isAdAvailable { return _appOpenAd != null; } } ``` -------------------------------- ### Handle Native Ad Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_platform_example/README.md Handles various native ad events including loading, failure, clicks, impressions, closing, opening, dismissal, and paid events. This snippet expands on the basic loading example by including more event listeners. ```dart bool _nativeAdIsLoaded = false; _nativeAd = NativeAd( adUnitId: _adUnitId, factoryId: "adFactoryExample", listener: NativeAdListener( onAdLoaded: (ad) { // ignore: avoid_print print('$NativeAd loaded.'); setState(() { _nativeAdIsLoaded = true; }); }, onAdFailedToLoad: (ad, error) { // ignore: avoid_print print('$NativeAd failedToLoad: $error'); ad.dispose(); }, // Called when a click is recorded for a NativeAd. onAdClicked: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when an ad removes an overlay that covers the screen. onAdClosed: (ad) {}, // Called when an ad opens an overlay that covers the screen. onAdOpened: (ad) {}, // For iOS only. Called before dismissing a full screen view onAdWillDismissScreen: (ad) {}, // Called when an ad receives revenue value. onPaidEvent: (ad, valueMicros, precision, currencyCode) {}, ), request: const AdRequest(), )..load(); ``` -------------------------------- ### Loading an AppOpenAd Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Demonstrates how to load an AppOpenAd using the `AppOpenAd.load()` method. It includes parameters for the ad unit ID, orientation, AdRequest, and a callback for handling load success or failure. This is crucial for pre-loading ads before they are needed. ```dart public class AppOpenAdManager { ... /// Load an [AppOpenAd]. void loadAd() { AppOpenAd.load( adUnitId: adUnitId, orientation: AppOpenAd.orientationPortrait, request: AdRequest(), adLoadCallback: AppOpenAdLoadCallback( onAdLoaded: (ad) { _appOpenAd = ad; }, onAdFailedToLoad: (error) { debugPrint('AppOpenAd failed to load: $error'); // Handle the error. }, ), ); } } ``` -------------------------------- ### Initialize Mobile Ads SDK and Check Adapter Status Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md Initializes the Mobile Ads SDK and logs the initialization status of each adapter. Ensure this completes before loading ads. ```dart void main() { WidgetsFlutterBinding.ensureInitialized(); MobileAds.instance.initialize() .then((initializationStatus) { initializationStatus.adapterStatuses.forEach((key, value) { debugPrint('Adapter status for $key: ${value.description}'); }); }); runApp(MyApp()); } ``` -------------------------------- ### Showing an AppOpenAd and Handling Callbacks Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Provides the implementation for showing an AppOpenAd if available and handling its lifecycle events via `FullScreenContentCallback`. This includes callbacks for when the ad is shown, fails to show, or is dismissed, ensuring proper ad management and subsequent ad loading. ```dart public class AppOpenAdManager { ... public void showAdIfAvailable() { if (!isAdAvailable) { debugPrint('Tried to show ad before available.'); loadAd(); return; } if (_isShowingAd) { debugPrint('Tried to show ad while already showing an ad.'); return; } // Set the fullScreenContentCallback and show the ad. _appOpenAd!.fullScreenContentCallback = FullScreenContentCallback( onAdShowedFullScreenContent: (ad) { _isShowingAd = true; debugPrint('$ad onAdShowedFullScreenContent'); }, onAdFailedToShowFullScreenContent: (ad, error) { debugPrint('$ad onAdFailedToShowFullScreenContent: $error'); _isShowingAd = false; ad.dispose(); _appOpenAd = null; }, onAdDismissedFullScreenContent: (ad) { debugPrint('$ad onAdDismissedFullScreenContent'); _isShowingAd = false; ad.dispose(); _appOpenAd = null; loadAd(); }, ); } } ``` -------------------------------- ### Handle Rewarded Ad Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_interstitial_example/README.md Shows how to set up a FullScreenContentCallback to manage various events for a rewarded interstitial ad, such as showing, impressions, failures, and dismissal. ```dart _rewardedInterstitialAd?.fullScreenContentCallback = FullScreenContentCallback( // Called when the ad showed the full screen content. onAdShowedFullScreenContent: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when the ad failed to show full screen content. onAdFailedToShowFullScreenContent: (ad, err) {}, // Called when the ad dismissed full screen content. onAdDismissedFullScreenContent: (ad) { ad.dispose(); }, // Called when a click is recorded for an ad. onAdClicked: (ad) {}); ``` -------------------------------- ### Initialize AdMob and AppLifecycleReactor Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Initialize Google Mobile Ads and set up the `AppLifecycleReactor` in your application's `main` function and `MyHomePage` state. ```dart import 'package:app_open_example/app_open_ad_manager.dart'; import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'app_lifecycle_reactor.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); MobileAds.instance.initialize(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'App Open Example', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'App Open Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } /// Example home page for an app open ad. class _MyHomePageState extends State { int _counter = 0; late AppLifecycleReactor _appLifecycleReactor; @override void initState() { super.initState(); AppOpenAdManager appOpenAdManager = AppOpenAdManager()..loadAd(); _appLifecycleReactor = AppLifecycleReactor(appOpenAdManager: appOpenAdManager); _appLifecycleReactor.listenToAppStateChanges();; } } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md Execute the unit tests for the google_mobile_ads package by navigating to its directory and running `flutter test`. ```bash cd packages/google_mobile_ads flutter test ``` -------------------------------- ### Handle Rewarded Ad Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_example/README.md Sets up callbacks for various ad events, such as showing, impressions, failures, dismissal, and clicks. Remember to dispose of the ad when dismissed. ```dart _rewardedAd?.fullScreenContentCallback = FullScreenContentCallback( // Called when the ad showed the full screen content. onAdShowedFullScreenContent: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when the ad failed to show full screen content. onAdFailedToShowFullScreenContent: (ad, err) {}, // Called when the ad dismissed full screen content. onAdDismissedFullScreenContent: (ad) { ad.dispose(); }, // Called when a click is recorded for an ad. onAdClicked: (ad) {}); ``` -------------------------------- ### Display Rewarded Ad and Handle Reward Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_interstitial_example/README.md Demonstrates how to display a loaded rewarded interstitial ad and handle the user reward using the show method and the onUserEarnedReward callback. ```dart _rewardedInterstitialAd?.show(onUserEarnedReward: (AdWithoutView ad, RewardItem rewardItem) { print('Reward amount: ${rewardItem.amount}'); }); ``` -------------------------------- ### Load Rewarded Interstitial Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_interstitial_example/README.md Demonstrates how to load a rewarded interstitial ad using the RewardedInterstitialAd.load method. It includes callbacks for successful loading and failure. ```dart RewardedInterstitialAd.load( adUnitId: _adUnitId, request: const AdRequest(), adLoadCallback: RewardedInterstitialAdLoadCallback( onAdLoaded: (RewardedInterstitialAd ad) { // Keep a reference to the ad so you can show it later. _rewardedInterstitialAd = ad; }, onAdFailedToLoad: (LoadAdError error) { print('RewardedInterstitialAd failed to load: $error'); }, )); ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md After making changes and ensuring they pass checks, commit your code with an informative message and push it to your origin branch. ```bash git commit -a -m "" git push origin ``` -------------------------------- ### Clone the Repository Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/CONTRIBUTING.md Clone the googleads-mobile-flutter repository to your local machine. Ensure you have an SSH key configured with GitHub for authentication. ```bash git clone git@github.com:/googleads-mobile-flutter.git ``` ```bash git remote add upstream git@github.com:googleads/googleads-mobile-flutter.git ``` -------------------------------- ### Display Rewarded Ad and Handle Reward Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_example/README.md Displays the loaded rewarded ad to the user and defines the callback for when the user earns a reward. The reward details are provided in the callback. ```dart _rewardedAd?.show(onUserEarnedReward: (AdWithoutView ad, RewardItem rewardItem) { print('Reward amount: ${rewardItem.amount}'); }); ``` -------------------------------- ### Load a Native Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_template_example/README.md Loads a native ad with specified ad unit ID and custom template styles. It includes a listener to handle ad loading success or failure. ```dart bool _nativeAdIsLoaded = false; _nativeAd = NativeAd( adUnitId: _adUnitId, listener: NativeAdListener( onAdLoaded: (ad) { print('$NativeAd loaded.'); setState(() { _nativeAdIsLoaded = true; }); }, onAdFailedToLoad: (ad, error) { print('$NativeAd failedToLoad: $error'); }, ), request: const AdRequest(), nativeTemplateStyle: NativeTemplateStyle( templateType: TemplateType.medium, mainBackgroundColor: const Color(0xfffffbed), callToActionTextStyle: NativeTemplateTextStyle( textColor: Colors.white, style: NativeTemplateFontStyle.monospace, size: 16.0), primaryTextStyle: NativeTemplateTextStyle( textColor: Colors.black, style: NativeTemplateFontStyle.bold, size: 16.0), secondaryTextStyle: NativeTemplateTextStyle( textColor: Colors.black, style: NativeTemplateFontStyle.italic, size: 16.0), tertiaryTextStyle: NativeTemplateTextStyle( textColor: Colors.black, style: NativeTemplateFontStyle.normal, size: 16.0))) ..load(); ``` -------------------------------- ### Manage App Open Ad Expiration Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Implement logic to track the ad load time and check if the ad has expired. If expired, reload the ad to ensure it's valid. ```dart /// Utility class that manages loading and showing app open ads. class AppOpenAdManager { ... /// Maximum duration allowed between loading and showing the ad. final Duration maxCacheDuration = Duration(hours: 4); /// Keep track of load time so we don't show an expired ad. DateTime? _appOpenLoadTime; ... /// Load an [AppOpenAd]. void loadAd() { AppOpenAd.load( adUnitId: adUnitId, orientation: AppOpenAd.orientationPortrait, request: AdRequest(), adLoadCallback: AppOpenAdLoadCallback( onAdLoaded: (ad) { debugPrint('$ad loaded'); _appOpenLoadTime = DateTime.now(); _appOpenAd = ad; }, onAdFailedToLoad: (error) { debugPrint('AppOpenAd failed to load: $error'); }, ), ); } /// Shows the ad, if one exists and is not already being shown. /// /// If the previously cached ad has expired, this just loads and caches a /// new ad. void showAdIfAvailable() { if (!isAdAvailable) { debugPrint('Tried to show ad before available.'); loadAd(); return; } if (_isShowingAd) { debugPrint('Tried to show ad while already showing an ad.'); return; } if (DateTime.now().subtract(maxCacheDuration).isAfter(_appOpenLoadTime!)) { debugPrint('Maximum cache duration exceeded. Loading another ad.'); _appOpenAd!.dispose(); _appOpenAd = null; loadAd(); return; } // Set the fullScreenContentCallback and show the ad. _appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(...); _appOpenAd!.show(); } } ``` -------------------------------- ### Load Native Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_platform_example/README.md Loads a native ad using the NativeAd class. Requires an ad unit ID and a factory ID. Handles ad loaded and failed to load events. ```dart bool _nativeAdIsLoaded = false; _nativeAd = NativeAd( adUnitId: _adUnitId, factoryId: "adFactoryExample", listener: NativeAdListener( onAdLoaded: (ad) { // ignore: avoid_print print('$NativeAd loaded.'); setState(() { _nativeAdIsLoaded = true; }); }, onAdFailedToLoad: (ad, error) { // ignore: avoid_print print('$NativeAd failedToLoad: $error'); ad.dispose(); }, ), request: const AdRequest(), )..load(); ``` -------------------------------- ### Android: AppLovin Privacy APIs Handler Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md Sets up a MethodChannel handler in the Android `MainActivity` to receive calls from Dart and interact with AppLovin privacy settings. Ensure the `CHANNEL_NAME` constant matches the Dart side. ```java public class MainActivity extends FlutterActivity { private static final String CHANNEL_NAME = "com.example.mediationexample/mediation-channel"; @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); // Setup a method channel for calling APIs in the AppLovin SDK. new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL) .setMethodCallHandler( (call, result) -> { switch (call.method) { case "setIsAgeRestrictedUser": AppLovinPrivacySettings.setIsAgeRestrictedUser(call.argument("isAgeRestricted"), context); result.success(null); break; case "setHasUserConsent": AppLovinPrivacySettings.setHasUserConsent(call.argument("hasUserConsent"), context); result.success(null); break; default: result.notImplemented(); break; } } ); } } ``` -------------------------------- ### Handle Interstitial Ad Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/interstitial_example/README.md Configure callbacks to manage the lifecycle of an interstitial ad, including when it's shown, dismissed, or fails to display. ```dart _interstitialAd?.fullScreenContentCallback = FullScreenContentCallback( // Called when the ad showed the full screen content. onAdShowedFullScreenContent: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when the ad failed to show full screen content. onAdFailedToShowFullScreenContent: (ad, err) {}, // Called when the ad dismissed full screen content. onAdDismissedFullScreenContent: (ad) { ad.dispose(); }, // Called when a click is recorded for an ad. onAdClicked: (ad) {}); ``` -------------------------------- ### Display a Native Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_template_example/README.md Displays a native ad using the AdWidget if the ad has been loaded successfully. The ad is rendered within a SizedBox with specified height and width. ```dart if (_nativeAdIsLoaded && _nativeAd != null) SizedBox( height: MediaQuery.of(context).size.width * _adAspectRatioMedium, width: MediaQuery.of(context).size.width, child: AdWidget(ad: _nativeAd!)), ``` -------------------------------- ### Registering iOS Mediation Network Extras Provider Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md This Objective-C code shows how to register a custom `FLTMediationNetworkExtrasProvider` with the `FLTGoogleMobileAdsPlugin` in your `AppDelegate`. This enables passing network-specific extras to mediation adapters. ```objectivec @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Register your network extras provider if you want to provide // network extras to specific ad requests. MyFLTMediationNetworkExtrasProvider *networkExtrasProvider = [[MyFLTMediationNetworkExtrasProvider alloc] init]; [FLTGoogleMobileAdsPlugin registerMediationNetworkExtrasProvider:networkExtrasProvider registry:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end @implementation MyFLTMediationNetworkExtrasProvider - (NSArray> *_Nullable)getMediationExtras:(NSString *_Nonnull)adUnitId mediationExtrasIdentifier: (NSString *_Nullable)mediationExtrasIdentifier { // This example passes extras to the applovin adapter. // This method is called with the ad unit of the associated ad request, and // an optional string parameter which comes from the dart ad request object. GADMAdapterAppLovinExtras *appLovinExtras = [[GADMAdapterAppLovinExtras alloc] init]; appLovinExtras.muteAudio = NO; return @[ appLovinExtras ]; } @end ``` -------------------------------- ### Handle Native Ad Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_template_example/README.md Handles various native ad events using the NativeAdListener, including ad loaded, failed to load, clicked, impression, closed, opened, will dismiss screen, and paid events. ```dart _nativeAd = NativeAd( adUnitId: _adUnitId, listener: NativeAdListener( onAdLoaded: (ad) { print('$NativeAd loaded.'); }, onAdFailedToLoad: (ad, error) { print('$NativeAd failedToLoad: $error'); }, // Called when a click is recorded for a NativeAd. onAdClicked: (ad) {}, // Called when an impression occurs on the ad. onAdImpression: (ad) {}, // Called when an ad removes an overlay that covers the screen. onAdClosed: (ad) {}, // Called when an ad opens an overlay that covers the screen. onAdOpened: (ad) {}, // For iOS only. Called before dismissing a full screen view onAdWillDismissScreen: (ad) {}, // Called when an ad receives revenue value. onPaidEvent: (ad, valueMicros, precision, currencyCode) {},** ), ... ``` -------------------------------- ### Load a Banner Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/banner_example/README.md Loads a banner ad with a specified ad unit ID and request. The listener handles callbacks for ad events, such as successful loading. ```dart BannerAd( adUnitId: _adUnitId, request: const AdRequest(), size: size, listener: BannerAdListener( // Called when an ad is successfully received. onAdLoaded: (ad) { setState(() { _bannerAd = ad as BannerAd; _isLoaded = true; }); }, ... ), ).load(); ``` -------------------------------- ### Display Native Ad Widget Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/native_platform_example/README.md Conditionally displays a native ad using the AdWidget if the ad is loaded and available. Sets the height and width for the ad container. ```dart if (_nativeAdIsLoaded && _nativeAd != null) SizedBox( height: HEIGHT, width: MediaQuery.of(context).size.width, child: AdWidget(ad: _nativeAd!)), ``` -------------------------------- ### iOS: AppLovin Privacy APIs Handler Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md Configures an `AppDelegate` in iOS to handle MethodChannel calls from Dart, enabling interaction with AppLovin privacy settings using `ALPrivacySettings`. The channel name must match the Dart implementation. ```objective-c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Set up a method channel for calling methods in 3P SDKs. FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* methodChannel = [FlutterMethodChannel methodChannelWithName:@"com.example.mediationexample/mediation-channel" binaryMessenger:controller.binaryMessenger]; [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { if ([call.method isEqualToString:@"setIsAgeRestrictedUser"]) { [ALPrivacySettings setIsAgeRestrictedUser:call.arguments[@"isAgeRestricted"]]; result(nil); } else if ([call.method isEqualToString:@"setHasUserConsent"]) { [ALPrivacySettings setHasUserConsent:call.arguments[@"hasUserConsent"]]; result(nil); } else { result(FlutterMethodNotImplemented); } }]; } @end ``` -------------------------------- ### Determine Adaptive Banner Ad Size Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/banner_example/README.md Calculates the appropriate adaptive banner ad size based on the current screen orientation and width. Use this to ensure your banner ad fits the available space. ```dart final size = await AdSize. getCurrentOrientationAnchoredAdaptiveBannerAdSize( MediaQuery.of(context).size.width.truncate()); ``` -------------------------------- ### Load a Rewarded Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/rewarded_example/README.md Loads a rewarded ad using the AdMob SDK. Ensure you have a valid ad unit ID and handle the load callback for success or failure. ```dart RewardedAd.load( adUnitId: _adUnitId, request: const AdRequest(), adLoadCallback: RewardedAdLoadCallback( onAdLoaded: (RewardedAd ad) { // Keep a reference to the ad so you can show it later. _rewardedAd = ad; }, onAdFailedToLoad: (LoadAdError error) { print('RewardedAd failed to load: $error'); }, )); ``` -------------------------------- ### Listen for App Foreground Events Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/app_open_example/README.md Subscribe to `AppStateEventNotifier.appStateStream` to receive notifications when the app is foregrounded. This is recommended over `WidgetsBindingObserver` for distinguishing app focus changes. ```dart import 'package:app_open_example/app_open_ad_manager.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; /// Listens for app foreground events and shows app open ads. class AppLifecycleReactor { final AppOpenAdManager appOpenAdManager; AppLifecycleReactor({required this.appOpenAdManager}); void listenToAppStateChanges() { AppStateEventNotifier.startListening(); AppStateEventNotifier.appStateStream .forEach((state) => _onAppStateChanged(state)); } void _onAppStateChanged(AppState appState) { if (appState == AppState.foreground) { appOpenAdManager.showAdIfAvailable(); } } } ``` -------------------------------- ### Registering Android Mediation Network Extras Provider Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md This Java code demonstrates how to register a custom `MediationNetworkExtrasProvider` with the `GoogleMobileAdsPlugin` in your `MainActivity`. This allows you to provide network-specific extras to mediation adapters. ```java public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); // Register your MediationNetworkExtrasProvider to provide network extras to ad requests. GoogleMobileAdsPlugin.registerMediationNetworkExtrasProvider( flutterEngine, new MyMediationNetworkExtrasProvider()); } } class MyMediationNetworkExtrasProvider implements MediationNetworkExtrasProvider { @Override public Map, Bundle> getMediationExtras( String adUnitId, @Nullable String identifier) { // This example passes extras to the applovin adapter. // This method is called with the ad unit of the associated ad request, and // an optional string parameter which comes from the dart ad request object. Bundle appLovinBundle = new AppLovinExtras.Builder().setMuteAudio(true).build(); Map, Bundle> extras = new HashMap<>(); extras.put(ApplovinAdapter.class, appLovinBundle); return extras; } } ``` -------------------------------- ### Dart: AppLovin Privacy APIs via Method Channel Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md Defines a Dart class that uses a MethodChannel to invoke AppLovin privacy APIs on native platforms. Requires setting up a corresponding handler in the native code. ```dart /// Wraps a method channel that makes calls to AppLovin privacy APIs. class MyMethodChannel { final MethodChannel _methodChannel = MethodChannel('com.example.mediationexample/mediation-channel'); /// Sets whether the user is age restricted in AppLovin. Future setAppLovinIsAgeRestrictedUser(bool isAgeRestricted) async { return _methodChannel.invokeMethod( 'setIsAgeRestrictedUser', { 'isAgeRestricted': isAgeRestricted, }, ); } /// Sets whether we have user consent for the user in AppLovin. Future setHasUserConsent(bool hasUserConsent) async { return _methodChannel.invokeMethod( 'setHasUserConsent', { 'hasUserConsent': hasUserConsent, }, ); } } ``` -------------------------------- ### Log Mediation Adapter Class Name for Banner Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/mediation_example/README.md Prints the mediation adapter class name for a loaded banner ad. This helps in identifying which ad network served the ad. ```dart final bannerAd = BannerAd( size: AdSize.banner, adUnitId: '', listener: BannerAdListener( onAdLoaded: (ad) { debugPrint('$ad loaded: ${ad.responseInfo?.mediationAdapterClassName}'); }, ), request: AdRequest(), ); ``` -------------------------------- ### Load Interstitial Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/interstitial_example/README.md Use this snippet to load an interstitial ad. It requires an ad unit ID and an AdRequest. The callback handles successful loads and failures. ```dart InterstitialAd.load( adUnitId: _adUnitId, request: AdRequest(), adLoadCallback: InterstitialAdLoadCallback( onAdLoaded: (InterstitialAd ad) { // Keep a reference to the ad so you can show it later. _interstitialAd = ad; }, onAdFailedToLoad: (LoadAdError error) { print('InterstitialAd failed to load: $error'); }, )); ``` -------------------------------- ### Display a Banner Ad in Flutter UI Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/banner_example/README.md Integrates a loaded banner ad into the Flutter widget tree, typically at the bottom of the screen. Ensures the ad is displayed only when loaded and within a safe area. ```dart Widget build(BuildContext context) { return MaterialApp( ... body: Stack( children: [ if (_bannerAd != null && _isLoaded) Align( alignment: Alignment.bottomCenter, child: SafeArea( child: SizedBox( width: _bannerAd!.size.width.toDouble(), height: _bannerAd!.size.height.toDouble(), child: AdWidget(ad: _bannerAd!), ), ), ) ], ) ), ); } ``` -------------------------------- ### Display Interstitial Ad Source: https://github.com/googleads/googleads-mobile-flutter/blob/main/samples/admob/interstitial_example/README.md Call this method to show a loaded interstitial ad to the user. ```dart _interstitialAd?.show(); ```