Search code examples
javaandroidlibgdxadmob

How to Show interstitial Ad on every 3 clicks in Android using LibGDX gaming framework


How i can show interstitial ad in every 3 button clicks. Here in my game I've interstitial show in RESTART button

Here is the code

In core module ...MAIN.java and layout main

@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);

    if (((Act) event.getTarget()).enabled) {
       if (event.getTarget().getName().equals("btnRestart")) {
            loadScreen("game");
            // show AdMob Interstitial
            nativePlatform.admobInterstitial();
            return;
       }
    ....
    } 

xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <com.google.android.gms.ads.AdView
        android:id="@+id/admob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_centerHorizontal="true"
        ads:adUnitId="@string/adMob_banner"
        ads:adSize="SMART_BANNER"/>


    <FrameLayout
        android:id="@+id/app"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </FrameLayout>

</LinearLayout>

there is no btn in layout


Solution

  • Take a static counter .

    public static int counter=0;
    

    Increase that counter on every click of your restart button. Use the remainder/modulus operator % to get your desired result.

    if (((Act) event.getTarget()).enabled) {
         if (event.getTarget().getName().equals("btnRestart")) {
                counter++;
                loadScreen("game");
                // show AdMob Interstitial
                if(counter%3==0) 
                  nativePlatform.admobInterstitial();
                return;
         }
        ....
    }