Ludicrous Software

Reloading AdMob Ads in Mobile AIR Apps

I recently released Marblous for the PlayBook, and decided to implement AdMob ad support using the method posted by Serge Jespers a while back (the basic approach is similar to the method I used for adding AdMob support to Corona apps a while back. It works quite nicely, but one of the things that I wanted to add to it is the ability to load a new ad at a regular interval.

There are different approaches that you can take to get this done. One approach would be to implement a timer in ActionScript to reload the ad html file. Another approach would also involve a timer (naturally), but to create the timer in JavaScript.

If you look at the code in Serge’s post, you’ll see that the main JavaScript call that actually loads the ad is this:

1
2
3
4
function showAd()
{
    _admob.fetchAd(document.getElementById('adspace'));
}

The basic goal, then, is to call the showAd() function at regular intervals. Since JavaScript doesn’t support a class like AS3’s Timer, I used setTimeout(), which is pretty much just like the setTimeout() function in ActionScript. The setTimeout() call is included in showAd(), and calls showAd(), so every time the function is called it creates a timeout that will call itself again:

1
2
_admob.fetchAd(document.getElementById('adspace'));
var t = setTimeout("showAd()", 60000);

The only problem is that when you test it on a device, it will actually look like it’s not loading a new ad, even though it does! When the new ad is loaded, the elements that make up the ad will get inserted into the adspace div below the current ad - if you add the setTimeout() call to your html file and load it up in your web browser, you’ll see what I mean. The problem from a Flash perspective is that the StageWebView instance has its viewPort set to match the size of the ad, so anything that gets inserted below the ad can’t be seen.

To fix this, we need to clear out all of the child elements from the adspace div before loading up the new ad:

1
2
3
4
5
6
var adDiv = document.getElementById('adspace');
while (adDiv.hasChildNodes()) {
    adDiv.removeChild(adDiv.lastChild);
}
_admob.fetchAd(document.getElementById('adspace'));
var t = setTimeout("showAd()", 60000);

And that should do it. In the case of AdMob, they recommend a refresh rate of one ad every 60 seconds, but if you want to use a different value, just modify the 60000 (milliseconds) to your desired value.