Monday, April 20, 2015

How-To use AdMob Interstitial Ads with Delphi XE7-XE8

Hi guys,
as you know by using the Delphi Android JNI you can access to Native features provided by Android SDK. The RAD Studio installation includes also Google Mobile ADS library (Androidapi.JNI.AdMob unit), as built-in java library for Android.
So by using this unit we can use the new Interstitials Ads provided by AdMob.
First of all rember to set to true the AdMob Service ( Project -> Entitlement List -> AdMob Service )



Let's start with the code.
Create an instance of TJInterstitialAd, wich is present in Androidapi.JNI.AdMob.
  
    FInterstitial := TJInterstitialAd.JavaClass.init(MainActivity);
    FInterstitial.setAdUnitId(StringToJString('Your-Publisher-ID'));

For example you can put the previous code in the FormCreate event. Then you have to use this code to display an Interstitial Ad (on button-click event in my demo):

var
  LADRequestBuilder: JAdRequest_Builder;
  LadRequest: JAdRequest;
begin
  LADRequestBuilder := TJAdRequest_Builder.Create;
  LADRequestBuilder.addTestDevice(MainActivity.getDeviceID);
  LadRequest := LADRequestBuilder.build();
  LAdViewListener := TMyAdViewListener.Create(FInterStitial);
  CallInUIThread(
    procedure
    begin
      FInterStitial.setAdListener(TJAdListenerAdapter.JavaClass.init
        (LAdViewListener));
      FInterStitial.loadAd(LadRequest);
    end);
end;

I used the TJAdRequest_Builder to create a request and set my device like a test device (see AdMob guidelines).
I also created a custom AdViewListener to intercept the interstitial events:
  • onAdClosed;
  • onAdFailedToLoad(errorCode: Integer);
  • onAdLeftApplication;
  • onAdOpened;
  • onAdLoaded;
TJAdListenerAdapter adapts my Listener class to Interstitial AdListener, this because I created a custom class to support interstitial events and show effectively the Ad when it was loaded.

TMyAdViewListener = class(TJavaLocal, JIAdListener)
  private
    FAD: JInterstitialAd;
  public
    constructor Create(AAD: JInterstitialAd);
    procedure onAdClosed; cdecl;
    procedure onAdFailedToLoad(errorCode: Integer); cdecl;
    procedure onAdLeftApplication; cdecl;
    procedure onAdOpened; cdecl;
    procedure onAdLoaded; cdecl;
  end;

procedure TMyAdViewListener.onAdLoaded;
begin
  FAD.show;
end;

Here the screenshot of interstitial on my phone:


This code should works also on AppMethod.
You can find the demo in my GitHub repository.

4 comments :

  1. Replies
    1. For this tutorial I've used only the existing bridge files available for Delphi. You can find the same units in include\android\rtl (path for C++) and use them in the same way I did.

      Delete
  2. Great tutorial, is there a link to download the demo project? (Delphi XE8)

    ReplyDelete
    Replies
    1. I have added the demo in my GitHub repository https://github.com/spinettaro/DelphiDemos

      Delete