Pages

Saturday, November 1, 2014

Tutorial: Add admob interstitial ads to your CoronaCards Windows Phone 8 app

Objective

Learn how to utilize Google Admob interstitial ads in your Corona windows phone 8 app.

Prerequisites

Tutorial

Note: You can download the completed sample app at the bottom of this page.

Acquire the Admob SDK for Windows Phone 8

Create a new Windows Phone 8 corona project

  • Open up Visual Studio and select File->New Project.
  • Select the Corona template at Templates->Visual C#->Corona
  • For Name: enter in "AdmobInterstitialTestApp"
  • For Location: you can put the project wherever you want. 



Set your target windows phone OS version to 8.0

Google admob only works with windows phone OS version 8.0 right now, NOT 8.1.
  • Open the project properties window by selecting PROJECT -> AdmobInterstitialTestApp Properties from the Visual Studio menu
  • Ensure the Target Windows Phone OS Version dropdown is set to Windows Phone OS 8.0


Add the Admob SDK to your project

  • In the Solution Explorer, right click References and select Add Reference
  • In the window that pops up, select Browse from the list on the left, then click the Browse button on the lower right. Navigate to the folder you unzipped the admob sdk into earlier, and select the file GoogleAds.dll. This will add a new entry into the main list. Click the box next to the GoogleAds.dll file and then click the OK button.

Create a wrapper class to show interstitial ads: InterstitialAdControl.cs

For convenience, we are going to create a class that will provide a simple interface to handle the interstitial ad logic. This will take care of creating a new InterstitialAd each time we want to show one, as well as printing out debug information from admob.

  • In the Solution Explorer, right click the project name and select Add -> Class
  • In the window that pops up, enter in InterstitialAdControl.cs for the name and click OK
  • Now replace the contents of the file with the following code:
using GoogleAds;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdmobInterstitialTestApp
{    
    class InterstitialAdControl
    {
        private InterstitialAd _interstitialAd;
        private string _appId;

        private bool _hasCalledLoadForInterstitialAd;
        public bool HasCalledLoadForInterstitialAd
        {
            get
            {
                return _hasCalledLoadForInterstitialAd;
            }
            private set
            {
                _hasCalledLoadForInterstitialAd = value;
            }
        }

        private bool _hasReceivedInterstitialAd;
        public bool HasReceivedInterstitialAd
        {
            get
            {
                return _hasReceivedInterstitialAd;
            }
            private set
            {
                _hasReceivedInterstitialAd = value;
            }
        }

        public InterstitialAdControl(string appId)
        {
            _appId = appId;
            _hasCalledLoadForInterstitialAd = false;
            _hasReceivedInterstitialAd = false;
        }

        public bool PreloadInterstitialAd()
        {
            _interstitialAd = new InterstitialAd(_appId);
            _interstitialAd.ReceivedAd += OnGoogleInterstitialAdReceived;
            _interstitialAd.FailedToReceiveAd += OnGoogleInterstitialAdFailedToReceiveAd;

            AdRequest adRequest = new AdRequest();
            _interstitialAd.LoadAd(adRequest);

            _hasCalledLoadForInterstitialAd = true;

            return true;
        }

        public void ShowAd()
        {
            if (_hasReceivedInterstitialAd == true)
            {
                _hasReceivedInterstitialAd = false;
                _hasCalledLoadForInterstitialAd = false;

                Debug.WriteLine("Showing interstitial ad...");
                _interstitialAd.ShowAd();
            }
            else
            {
                // Just have to miss this one.
                Debug.WriteLine("Google has not indicated an ad is loaded. Nothing to show.");
            }
        }

        private void OnGoogleInterstitialAdReceived(object sender, AdEventArgs e)
        {
            Debug.WriteLine("Received google interstitial ad...");
            _hasReceivedInterstitialAd = true;
        }

        private void OnGoogleInterstitialAdFailedToReceiveAd(object sender, AdErrorEventArgs e)
        {
            Debug.WriteLine("ERROR: google interstitial ad error ... " + e.ToString());
        }
    }    
}


  • Now open MainPage.xaml.cs. We need to instantiate our class so that we can use it later.
  • Just below the MainPage class declaration add the line:
private InterstitialAdControl _interstitialAdControl;
  • Now inside the MainPage constructor ad the following line:
_interstitialAdControl = new InterstitialAdControl("YOUR_INTERSTITIAL_APP_ID_HERE");

The YOUR_INTERSTITIAL_APP_ID_HERE should be substituted with your real admob interstitial app id.

Construct the Lua to C# bridge code

We next need to create the code that will allow us to interact with our InterstitialAdControl object. This is referred to as the bridge code. First we'll construct the listener methods we want to be able to call from Lua.

  • Add the following lines to the top of MainPage.xaml.cs:
using CoronaLabs.Corona.WinRT;
using System.Diagnostics;
  • Add the following code to the end of the MainPage class definition:
public ICoronaBoxedData Native_PreloadInterstitialAd_Listener(CoronaRuntimeEnvironment sender, CoronaLuaEventArgs e)
        {
            Debug.WriteLine("Loading google interstitial ad...");
            _interstitialAdControl.PreloadInterstitialAd();

            return CoronaBoxedBoolean.True;
        }

        public ICoronaBoxedData Native_IsInterstitialAdPreloaded_Listener(CoronaRuntimeEnvironment sender, CoronaLuaEventArgs e)
        {
            if (_interstitialAdControl.HasReceivedInterstitialAd == true)
            {
                return CoronaBoxedBoolean.True;
            }
            else
            {
                return CoronaBoxedBoolean.False;
            }
        }

        public ICoronaBoxedData Native_ShowInterstitialAd_Listener(CoronaRuntimeEnvironment sender, CoronaLuaEventArgs e)
        {
            _interstitialAdControl.ShowAd();

            return CoronaBoxedBoolean.True;
        }


We have now defined the methods that we want to call from Lua, but corona still doesn't know about them. Let's fix that by adding in the necessary listeners:
  • At the end of the MainPage constructor, add the following:
// Add a Corona event handler which detects when the Corona project has been loaded, but not started yet.
fCoronaPanel.Runtime.Loaded += OnCoronaRuntimeLoaded;

  • After the constructor, add the following method:
/// <summary>
        ///  Called when a new CoronaRuntimeEnvironment has been created/loaded,
        ///  but before the "main.lua" has been executed.
        /// </summary>
        /// <param name="sender">The CoronaRuntime object that raised this event.</param>
        /// <param name="e">Event arguments providing the CoronaRuntimeEnvironment that has been created/loaded.</param>
        private void OnCoronaRuntimeLoaded(object sender, CoronaLabs.Corona.WinRT.CoronaRuntimeEventArgs e)
        {
            // Register bridges with corona.            
            e.CoronaRuntimeEnvironment.AddEventListener("Native_PreloadInterstitialAd", Native_PreloadInterstitialAd_Listener);
            e.CoronaRuntimeEnvironment.AddEventListener("Native_IsInterstitialAdPreloaded", Native_IsInterstitialAdPreloaded_Listener);
            e.CoronaRuntimeEnvironment.AddEventListener("Native_ShowInterstitialAd", Native_StartInterstitialAd_Listener);
        }

Now corona knows what native methods to invoke when we raise a specific event with the Lua code.


Create buttons in the corona app to preload and display an interstitial ad

Now that we have our native code setup, we need to call that code from our corona lua app. For the sake of the example, let's create a button in our corona app that will display an interstitial ad when pressed.
  • Open Assets/Corona/main.lua and add the following code at the end of the file:
local widget = require("widget")
local preloadAdButton = widget.newButton{
label="Preload Ad",
labelColor = { default={1,0,0}, over={0,1,0} },
fontSize = 32,
width=200, height=50,
onRelease = preloadAdButton_onReleaseListener,
x = display.contentCenterX, y = display.contentCenterY + 100,
}  

local displayAdButton = widget.newButton{
label="Display Ad",
labelColor = { default={1,0,0}, over={0,1,0} },
fontSize = 32,
width=200, height=50,
onRelease = displayAdButton_onReleaseListener,
x = display.contentCenterX, y = display.contentCenterY + 150,
}  

Compile your windows phone 8 app and deploy it to your device

NOTE: 
  • Build your windows phone 8 app by selecting BUILD -> Build Solution from the Visual Studio menu.
  • When the build has finished, deploy the app to your windows phone 8 device by selecting DEBUG -> Start Debugging from the Visual Studio menu.

Test the App

Your app should have automatically started from the previous step. Now you can use the touch buttons to preload an interstitial ad, and then display that ad. You can watch the Visual Studio Output window to see what's going on. Your output should look something like this:

>>Touch the Preload Ad button
Loading google interstitial ad...
Received google interstitial ad...
>>Touch the Display Ad button
Showing interstitial ad...

NOTE: It will take a number of seconds (probably between 3 -> 10 seconds) the first time from when you begin the ad preload to when you receive an ad back from google. After the first time, this time window shrinks to a second or two.

NOTE: You'll probably see some exceptions happen in the output, but that seems to be coming from inside the GoogleAds.dll so you don't need to worry about it. 

Below are some screenshots of the app in action:




Conclusion

That's all there is to it! You have now successfully integrated admob interstitial ads into your windows phone 8 corona app. You can now preload and display those ads from your lua code! Congrats! :D

Resources

The completed sample application can be downloaded here.