1,首先添加一个全局的生命周期监听类
class AppLifecycleObserver with WidgetsBindingObserver {
bool IsCold = false;
bool isAgree = false;
void getIsCold() async {
isAgree = await SPManager().getBool(SPKeys.isAgreePrivacy, defaultValue: true);
IsCold = await SPManager().getBool("isCold", defaultValue: false);
}
Future<bool> getIsVipPay() async {
return await SPManager().getBool('isVipPay', defaultValue: false);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
getIsCold();
if(!isAgree) {
if (state == AppLifecycleState.resumed) {
if (!IsCold) {
//热启动开屏广告
IdcardAndroid().showSplashAd(AdsConfig.splashId);
SPManager().setBool("isCold", true);
} else {
SPManager().setBool("isCold", AdsConfig.isPayBack? true: false);
}
SPManager().getBool(SPKeys.isShowPayPage, defaultValue: false).then((value) => {
if (value){
//满足条件开始计时
GlobalAdsTimer.showScreenAds()
}
});
}
}
if (state == AppLifecycleState.paused){
//退入后台时停止广告计时
GlobalAdsTimer.stop();
} else if (state == AppLifecycleState.detached) {
}
}
}
在main()入口绑定 就可以监测到了 全局的生命周期
`WidgetsBinding.instance.addObserver(AppLifecycleObserver());
2,定义一个全局的计时器 GlobalAdsTimer()
class GlobalAdsTimer {
static Timer? timerHalfScreen;
//展示广告
static void start() {
timerHalfScreen?.cancel();
timerHalfScreen = null;
timerHalfScreen = Timer.periodic(const Duration(minutes: 3), (timer) {
showTodayHalfScreenVideo();
setRealSystemUIOverlayStyle = true;
addTodayHalfScreenNumVideo();
timerHalfScreen?.cancel();
timerHalfScreen = null;
GroMoreManager().showInterstitialAd((b){
//如果当前有前一个插屏广告未关闭就不继续请求
if (b){
showScreenAds();
}
});
});
}
//展示条件
static void showScreenAds() {
print('GlobalAdsTimer_showScreenAds');
GroMoreManager().isShowHomeInterstitialAd().then((value) => {
if (value) {
getShowTodayHalfScreenVideo().then((value) => {
if (value) {
clearTodayHalfScreenNumVideo(0),
},
getShowTodayHalfScreenNumVideo().then((int num) => {
if (num < 5) {
start(),
} else {
timerHalfScreen?.cancel(),
timerHalfScreen = null,
}
})
})
}
});
}
// 停止广告 应用退入后台/进入通用付费页/引导付费页 停止计时
static void stop() {
print('GlobalAdsTimer_stop');
timerHalfScreen?.cancel();
}
3,当进入特殊页面禁止弹出插屏广告,例如付费页禁止弹出影响用户付费率时
VipPage
@override
void initState() {
super.initState();
//停止计时
GlobalAdsTimer.stop();
}
页面销毁时开始
@override
void dispose() {
super.dispose();
GlobalAdsTimer.showScreenAds();
}