Reputation: 3471
I would like to add AdMob ads to my application, but I have a problem with showing/hiding them depending on the internet connection status of the device. When I turn on my device with WiFi turned on the ad is shown correctly, when I turn the WiFi off, the ad is hiding also corectly. But when I go from "no internet" state to WiFi/3G on the ad is not showing. Instead I get suchmessages in Logcat:
04-15 13:16:03.688 8813-8813/com.package.app I/Ads﹕ Ad is not visible. Not refreshing ad.
04-15 13:16:03.688 8813-8813/com.package.app I/Ads﹕ Scheduling ad refresh 60000 milliseconds from now.
Activity's code:
@Override
protected void onCreate(Bundle savedInstanceState) {
/***/
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
super.onAdLoaded();
}
@Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
mAdView.setVisibility(View.GONE);
}
});
}
@Override
protected void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
@Override
protected void onPause() {
super.onPause();
if (mAdView != null) {
mAdView.pause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mAdView != null) {
mAdView.destroy();
}
}
I would like to turn the ads on and make the AdView
visible when the user turns the internet connection on, and hide it when the user loses the internet connection. What's wrong with my approach? Is it possibile to do this without internet connectivity state listener?
Upvotes: 1
Views: 2412
Reputation: 636
If anybody still has problem with that, this code will check every REFRESH_RATE_IN_SECONDS if can get new ad when internet is off. Code is taken from here.
private int REFRESH_RATE_IN_SECONDS = 5;
AdView adView;
private final Handler refreshHandler = new Handler();
private final Runnable refreshRunnable = new RefreshRunnable();
AdRequest adRequest;
@Override
public void onCreate() {
super.onCreate();
adView = (AdView) findViewById(R.id.adView);
adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
adView.setAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(int errorCode){
refreshHandler.removeCallbacks(refreshRunnable);
refreshHandler.postDelayed(refreshRunnable, REFRESH_RATE_IN_SECONDS * 1000);
}
});
adView.loadAd(adRequest);
}
private class RefreshRunnable implements Runnable {
@Override
public void run() {
adView.loadAd(adRequest);
}
}
Upvotes: 3
Reputation: 61
i had same problem but i do a simple hack..hope this will help but i don't think this is good approach because adview is continuously requesting ads.
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
adView.loadAd(adRequest);
}
Upvotes: 0