구글 공식 문서
Flutter Admob 연동
구글 공식 문서에는 Flutter Admob베타 버전이 작성되어있는데, 따라만 한다면 금방 할 수 있을 것이다. 그리고 이전 포스트에서 Flutter 연동하는 법을 정리했다.
메인 페이지에서 쓰일 컨트롤러를 선언해준다. SuperController을 상속하여 Getx의 생명주기 콜백함수를 사용할 수 있도록 해야 한다.
onResumed()시에 오프닝 광고가 출력되도록 했다.
class MainPageController extends SuperController {
late AppOpenAdManager appOpenAdManager;
final List<Widget> widgetList = [
CalendarPage(),
SummaryPage(),
// InformationPage(),
];
int currentIndex = 0;
void onInit() {
super.onInit();
appOpenAdManager = AppOpenAdManager()..loadAd();
WidgetsBinding.instance!
.addObserver(AppLifecycleReactor(appOpenAdManager: appOpenAdManager));
}
void onChanged(value) {
currentIndex = value;
update();
}
void onDetached() {
print("onDetached");
}
void onInactive() {
print("onInactive");
}
void onPaused() {
print("opPaused");
}
void onResumed() {
print("onResumed");
appOpenAdManager.showAdIfAvailable();
}
}
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:mobile/utils/ad_helper.dart';
class AppOpenAdManager {
String adUnitId = AdHelper.openningAdUnitId;
AppOpenAd? _appOpenAd;
bool _isShowingAd = false;
final Duration maxCacheDuration = Duration(hours: 4);
DateTime? _appOpenLoadTime;
void loadAd() {
AppOpenAd.load(
adUnitId: adUnitId,
orientation: AppOpenAd.orientationPortrait,
request: AdRequest(),
adLoadCallback: AppOpenAdLoadCallback(
onAdLoaded: (ad) {
_appOpenAd = ad;
_appOpenLoadTime = DateTime.now();
},
onAdFailedToLoad: (error) {
print('AppOpenAd failed to load: $error');
},
),
);
}
bool get isAdAvailable {
return _appOpenAd != null;
}
void showAdIfAvailable() {
if (!isAdAvailable) {
print('Tried to show ad before available.');
loadAd();
return;
}
if (_isShowingAd) {
print('Tried to show ad while already showing an ad.');
return;
}
if (DateTime.now().subtract(maxCacheDuration).isAfter(_appOpenLoadTime!)) {
print('Maximum cache duration exceeded. Loading another ad.');
_appOpenAd!.dispose();
_appOpenAd = null;
loadAd();
return;
}
_appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) {
_isShowingAd = true;
print('$ad onAdShowedFullScreenContent');
},
onAdFailedToShowFullScreenContent: (ad, error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
},
onAdDismissedFullScreenContent: (ad) {
print('$ad onAdDismissedFullScreenContent');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
loadAd();
},
);
_appOpenAd!.show();
}
}
class AppLifecycleReactor extends WidgetsBindingObserver {
final AppOpenAdManager appOpenAdManager;
AppLifecycleReactor({required this.appOpenAdManager});
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed) {
appOpenAdManager.showAdIfAvailable();
}
}
}