Show interstitial ad more than once admob - iphone

Ive been trying to display an interstitial ad several times during my app runtime. Ive read admob documentation about it and it seems that is a one-time-use object, I'd like to know if there's any workaround for this. Any help will be appreciated. Thanks

I know the question is about 8 years ago but I had the same problem. What worked for me:
import 'package:firebase_admob/firebase_admob.dart';
InterstitialAd _interstitialAd;
bool _isInterstitialAdReady;
void prepAd(){
initState();
_loadInterstitialAd();
}
void runAd() {
_interstitialAd.show();
}
void initState() {
_isInterstitialAdReady = false;
_interstitialAd = InterstitialAd(
adUnitId: InterstitialAd.testAdUnitId,
listener: _onInterstitialAdEvent,
);
}
void _loadInterstitialAd() {
_interstitialAd.load();
}
// TODO: Implement _onInterstitialAdEvent()
void _onInterstitialAdEvent(MobileAdEvent event) {
switch (event) {
case MobileAdEvent.loaded:
_isInterstitialAdReady = true;
break;
case MobileAdEvent.failedToLoad:
_isInterstitialAdReady = false;
print('Failed to load an interstitial ad');
break;
case MobileAdEvent.closed:
dispose();
prepAd();
break;
default:
// do nothing
}
}
void dispose() {// TODO: Dispose InterstitialAd object
_interstitialAd?.dispose();
}
I ran prepAd() once in the beginning and then just runAd() when I need it. You can check _isInterstitialAdReady == true inside runAd() if you want

Related

adUnitId is not showing google banner ads in flutter

I'm trying to implement google ads through admob_flutter package, created adunitId through admob account. but these adUnitId are not showing ads.
when I'm using ca-app-pub-3940256099942544/2934735716 this adUnitId then it is showing test ads on google ad.
Here is my code:
import 'dart:async';
import 'dart:io';
import 'package:admob_flutter/admob_flutter.dart';
import 'package:flutter/material.dart';
class GoogleAdBanner extends StatefulWidget {
GoogleAdBanner(this.size);
final AdmobBannerSize size;
#override
State<StatefulWidget> createState() => BannerAdState();
}
class BannerAdState extends State<GoogleAdBanner> {
AdmobBanner _bannerAd;
final Completer<AdmobBanner> bannerCompleter = Completer<AdmobBanner>();
#override
void initState() {
super.initState();
Admob.requestTrackingAuthorization();
}
String getBannerAdUnitId() {
if (Platform.isIOS) {
return 'ca-app-pub-7282911616152886/6377817226';
} else if (Platform.isAndroid) {
return 'ca-app-pub-7282911616152886/8046122111';
}
return null;
}
void handleEvent(
AdmobAdEvent event, Map<String, dynamic> args, String adType) {
switch (event) {
case AdmobAdEvent.loaded:
print('New Admob $adType Ad loaded!');
break;
case AdmobAdEvent.opened:
print('Admob $adType Ad opened!');
break;
case AdmobAdEvent.closed:
print('Admob $adType Ad closed!');
break;
case AdmobAdEvent.failedToLoad:
print('Admob $adType failed to load. :(');
break;
default:
}
}
#override
Widget build(BuildContext context) {
return AdmobBanner(
adUnitId: getBannerAdUnitId(), //'ca-app-pub-3940256099942544/2934735716',
adSize: widget.size,
listener: (AdmobAdEvent event,
Map<String, dynamic> args) {
handleEvent(event, args, 'Banner');
},
onBannerCreated: (AdmobBannerController controller) {},
);
}
}
using it as
GoogleAdBanner(AdmobBannerSize.LARGE_BANNER)
Please help with this. Thanks in advance!
Real ads are displayed only when there are enough number of requests. The inventory is empty till the threshold has reached. If you are able to see the test ads you can be assured that the implementation is right. Make sure you change the ad app id in manifest and info.plist and add the right ad unit ad in ad request before release.
use getBannerAdUnitId() like this:-
String get BannerAdUnitId(){
//body
}
adUnitId: BannerAdUnitId(),

Multiple audioplayers keep playing on Flutter

I have an app on Flutter with different tabs and on each tab basically I have a different audioplayer. By the way I use the "audioplayers.dart" package.
When the user changes tab, I want the audioplayer to stop. So I put a stop() function in the dispose method.
However, sometimes this isn't working because of states issues.
I wonder if there is an easiest way by forbidding maybe an audioplayer to be play when the user is on another page ?
late AudioPlayer audioplayer;
#override
void initState() {
super.initState();
audioplayer = AudioPlayer(playerId: 'liked_musics');
audioplayer.onDurationChanged.listen((Duration d) {
setState(() => duree = d);
});
audioplayer.onAudioPositionChanged.listen((Duration d) {
setState(() => position = d);
});
audioplayer.onPlayerCompletion.listen((event) {
setState(() {
position = duree;
statut = PlayerState.STOPPED;
});
});
}
#override
dispose() {
audioplayer.stop();
}
Thank you for your help
Joffrey
You can use event bus package
Sample pseudo code:
class AudioStopEvent {
int clickedTabPosition;
AudioStopEvent(this.clickedTabPosition);
}
class BusHelper {
static EventBus eventBus = new EventBus();
}
class YourTabPage{
#override
void initState() {
super.initState();
BusHelper.eventBus.on<AudioStopEvent>().listen((event) {
if(event.clickedTabPosition != currentPagePosition)
audio.stop();
});
}
}
class YourTabManagementClass{
whenChangeTabPage(){
BusHelper.eventBus.fire(new AudioStopEvent(clickedPagePosition)); }
}

Flutter interstitial ad with AppOpen ads

Currently Im using native_admob_flutter for my flutter app. I also included AppOpenAds and Interstital ad within the app.
I want to display the AppOpen ad when user open the app/ resume to the app, here is how I do it in main.dart:
#override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.resumed:
loadAndDisplayAppOpenAd();
break;
case AppLifecycleState.inactive:
break;
case AppLifecycleState.paused:
break;
case AppLifecycleState.detached:
break;
}
}
However I found that displaying Interstial ad will also change the app state -> inactive -> paused -> resume, which trigger AppOpen ad.
This really create bad user experinence. Is there a way to overcome this? Thank you!
You may need a variable to make sure that app has been paused by user action, and not by interstitial.
static bool pausedByInterstitial = false;
...
class AppLifecycleReactor extends WidgetsBindingObserver {
final AppOpenAdManager appOpenAdManager;
AppLifecycleReactor({required this.appOpenAdManager});
static bool pausedByInterstitial = false;
#override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed && !pausedByInterstitial) {
appOpenAdManager.showAdIfAvailable();
}
}
}
...
showInter() {
AppLifecycleReactor.pausedByInterstitial = true;
InterstitialListener(
...
onAdHiddenCallback: (ad) {
AppLifecycleReactor.pausedByInterstitial = false;
},
...
);
}

How to open another page after rewarded ad is watched in Flutter?

Flutter App.
One button that leads to the 2nd page where the content is.
The user clicks on the button and must watch a video ad(rewarded ad).
After the video ad finishes > the user can open the 2nd page / or the 2nd page will be automatically opened when he clicks 'x' on the finished video ad.
My question is > how to do this? What would the code look like and what to use?
Thank you!
Use the following code on your first page above the build method
late RewardedAd _rewardedAd;
bool _isRewardedAdReady = false;
// TODO: Implement _loadRewardedAd()
void _loadRewardedAd() {
RewardedAd.load(
adUnitId: AdHelper.rewardedAdUnitId,
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (ad) {
this._rewardedAd = ad;
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
setState(() {
_isRewardedAdReady = false;
});
_loadRewardedAd();
},
);
setState(() {
_isRewardedAdReady = true;
});
},
onAdFailedToLoad: (err) {
print('Failed to load a rewarded ad: ${err.message}');
setState(() {
_isRewardedAdReady = false;
});
},
),
);
}
After that initialize and dispose the rewardedad like
#override
void initState() {
_loadRewardedAd();
super.initState();
}
#override
void dispose() {
_rewardedAd.dispose();
super.dispose();
}
Now call the rewarede ad with Navigating to othe page
GestureDetector(
onTap: () {
if(_isRewardedAdReady){
_rewardedAd.show(onUserEarnedReward:
(RewardedAd ad, RewardItem reward) {
print(
'$ad with reward $RewardItem(${reward.amount}, ${reward.type}');
});
}
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context)=>SecondPage()));
},
child: CustomButton(text:'GoTo Second Page')
),
for better understand go to here

Pass Widgets in Connectivity check in flutter

I want to implement internet connectivity check into my app and I used official connectivity plugin and it is working great for displaying String Value but instead of showing string value in screen I want to display different widgets for connected and disconnected.
Here What I am Using
//
Widget result;
//
body: Container(
alignment: Alignment.center,
child: result != null ?
result : Text("unknown", style :
TextStyle(fontSize: 30,fontWeight: FontWeight.bold),
),
void checkStatus(){
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
if(
result == ConnectivityResult.mobile ||
result == ConnectivityResult.wifi){
Text("Connected", style:TextStyle(color:Colors.red));
} else {
Text("No InterNet", style:TextStyle(color:Colors.red));
}
});
}
#override
void initState() {
super.initState();
checkStatus();
}
And I am Getting 'unknown' value
try this
class Sample extends StatefulWidget {
#override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
Widget result;
#override
void initState() {
super.initState();
checkStatus();
}
void checkStatus() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
result = Text("Connected to Mobile Network");
setState(() {});
} else if (connectivityResult == ConnectivityResult.wifi) {
result = Text("Connected to WiFi");
print("Connected to WiFi");
setState(() {});
} else {
result = Text("Unable to connect. Please Check Internet Connection");
setState(() {});
print("Unable to connect. Please Check Internet Connection");
}
}
#override
Widget build(BuildContext context) {
return Center(child: result);
}
}
Try this:
Use this package for checking Internet:
data_connection_checker:
And, Inside your stateful class create stream listener i.e and a boolean value.
StreamSubscription<DataConnectionStatus> listener; bool isConnected = true;
and Inside initState:
#override
void initState() {
super.initState();
listener = DataConnectionChecker().onStatusChange.listen((status) {
switch (status) {
case DataConnectionStatus.connected:
print('Data connection is available. $status');
setState(() {
isConnected = true;
});
break;
case DataConnectionStatus.disconnected:
print('You are disconnected from the internet. $status');
setState(() {
isConnected = false;
});
break;
}
});
}
Done, This will keep listening to changes in your internet status, Thus you can prompt user as you like. Cheers, Feel free to ask if confusion and if it helps upvote :D