Search code examples
libgdxadmob

how to add ( admob ) Interstitial ads to libgdx game and what activity to use?


I followed google guide:

  1. updated build.gradle dependencies
  2. updated AndroidManifest.xml
  3. updated the AndroidLauncher and tried banner ads first from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
@Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Create the layout
RelativeLayout layout = new RelativeLayout(this);

// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);

// Create and setup the AdMob view

AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here

AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);

// Add the libGDX view
layout.addView(gameView);

// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

layout.addView(adView, adParams);

// Hook it all up
setContentView(layout);
}}

but I cant figure out how to do the same for Interstitial ads

i tried adding adscontroller interface

public interface AdsController {
    public void loadInterstitialAd();
    public void showInterstitialAd();
}

and updating AndroidLauncher

public class AndroidLauncher extends AndroidApplication implements AdsController  {



    InterstitialAd mInterstitialAd;
    private static final String TAG = "Androidlauncher";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // // Create the layout
       RelativeLayout layout = new RelativeLayout(this);
                // Do the stuff that initialize() would do for you
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        // Create the libGDX View
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        View gameView = initializeForView(new mygame(this), config);
        layout.addView(gameView);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {}
        });

        AdRequest adRequest = null;
        InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
                new InterstitialAdLoadCallback() {
                    @Override
                    public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                        // The mInterstitialAd reference will be null until
                        // an ad is loaded.
                        mInterstitialAd = interstitialAd;
                        Log.i(TAG, "onAdLoaded");
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        // Handle the error
                        Log.d(TAG, loadAdError.toString());
                        mInterstitialAd = null;
                    }
                });

        mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
            @Override
            public void onAdClicked() {
                // Called when a click is recorded for an ad.
                Log.d(TAG, "Ad was clicked.");
            }

            @Override
            public void onAdDismissedFullScreenContent() {
                // Called when ad is dismissed.
                // Set the ad reference to null so you don't show the ad a second time.
                Log.d(TAG, "Ad dismissed fullscreen content.");
                mInterstitialAd = null;
            }

            @Override
            public void onAdFailedToShowFullScreenContent(AdError adError) {
                // Called when ad fails to show.
                Log.e(TAG, "Ad failed to show fullscreen content.");
                mInterstitialAd = null;
            }

            @Override
            public void onAdImpression() {
                // Called when an impression is recorded for an ad.
                Log.d(TAG, "Ad recorded an impression.");
            }

            @Override
            public void onAdShowedFullScreenContent() {
                // Called when ad is shown.
                Log.d(TAG, "Ad showed fullscreen content.");
            }

        });
        loadInterstitialAd();
    }

    @Override
    public void loadInterstitialAd() {
        AdRequest adRequest = new AdRequest.Builder().build();

    }

    @Override
    public void showInterstitialAd() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mInterstitialAd!=null) {
                    mInterstitialAd.show();
                }
                else loadInterstitialAd();
            }
        });


    }
}

InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?) every code I found is no longer useful because google updated Admob


Solution

  • AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);

    I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:

    public interface AdManager {
    
        /**
         * Show a rewarded video ad
         */
        void showRewardedVideo();
    
        /**
         * Called on app pause
         */
        void onPause();
    
        /**
         * Called on app resume
         */
        void onResume();
    
        /**
         * Attempts to show an interstitial ad
         *
         * @param onSuccess
         * @param onFailed
         */
        void showInterstitial(Listener onSuccess, Listener onFailed);
    
        /**
         * Called every frame, for any extra work that might need to be done
         *
         * @param deltaTime
         */
        void update(float deltaTime);
    }
    

    Following that, you can implement your platform's ad provider:

    public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
    
    
        private OnlineRPG game;
        private boolean videoAvailable;
    
        private Listener onInterstitialSuccess;
        private Listener onInterstitialFailed;
    
        private float timeSinceAd;
    
        public AndroidAdManager(Activity activity, Gamegame) {
            this.game = game;
            this.activity = activity;
    
            IronSource.setRewardedVideoListener(this);
            IronSource.setInterstitialListener(this);
            IronSource.setOfferwallListener(this);
            IronSource.init(activity, "whatever");
            IronSource.shouldTrackNetworkState(activity, true);
            IronSource.loadInterstitial();
            IntegrationHelper.validateIntegration(activity);
        }
    
        @Override
        public void showRewardedVideo() {
            if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
                Log.i(TAG, "Rewarded video placement is capped");
                return;
            }
            IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
        }
    
        @Override
        public void onPause() {
            IronSource.onPause(activity);
        }
    
        @Override
        public void onResume() {
            IronSource.onResume(activity);
        }
    
        @Override
        public void showInterstitial(Listener onSuccess, Listener onFailed) {
            if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
                onFailed.invoke();
                return;
            }
            this.onInterstitialSuccess = onSuccess;
            this.onInterstitialFailed = onFailed;
            IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
        }
    
        @Override
        public void update(float deltaTime) {
            timeSinceAd += deltaTime;
        }
    
        @Override
        public void onRewardedVideoAdOpened() {
    
        }
    
        @Override
        public void onRewardedVideoAdClosed() {
    
        }
    
        @Override
        public void onRewardedVideoAvailabilityChanged(boolean b) {
            Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
            videoAvailable = b;
        }
    
        @Override
        public void onRewardedVideoAdStarted() {
    
        }
    
        @Override
        public void onRewardedVideoAdEnded() {
    
        }
    
        @Override
        public void onRewardedVideoAdRewarded(Placement placement) {
    
        }
    
        @Override
        public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
    
        }
    
        @Override
        public void onRewardedVideoAdClicked(Placement placement) {
    
        }
    
        @Override
        public void onInterstitialAdReady() {
    
        }
    
        @Override
        public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
            if (onInterstitialFailed != null) {
                Gdx.app.postRunnable(new Runnable() {
                    @Override
                    public void run() {
                        onInterstitialFailed.invoke();
                        onInterstitialFailed = null;
                    }
                });
            }
        }
    
        @Override
        public void onInterstitialAdOpened() {
            Log.i(TAG, "Interstitial Ad Opened");
        }
    
        @Override
        public void onInterstitialAdClosed() {
            Log.i(TAG, "Interstitial Ad Closed");
            if (onInterstitialSuccess != null) {
                Gdx.app.postRunnable(new Runnable() {
                    @Override
                    public void run() {
                        timeSinceAd = 0;
                        onInterstitialSuccess.invoke();
                        onInterstitialSuccess = null;
                    }
                });
            }
            IronSource.loadInterstitial();
        }
    
        @Override
        public void onInterstitialAdShowSucceeded() {
    
        }
    
        @Override
        public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
            Log.e(TAG, ironSourceError.getErrorMessage());
            if (onInterstitialFailed != null) {
                Gdx.app.postRunnable(new Runnable() {
                    @Override
                    public void run() {
                        onInterstitialFailed.invoke();
                        onInterstitialFailed = null;
                    }
                });
            }
        }
    
        @Override
        public void onInterstitialAdClicked() {
    
        }
    
        @Override
        public void onOfferwallAvailable(boolean b) {
    
        }
    
        @Override
        public void onOfferwallOpened() {
    
        }
    
        @Override
        public void onOfferwallShowFailed(IronSourceError ironSourceError) {
    
        }
    
        @Override
        public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
            return false;
        }
    
        @Override
        public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
    
        }
    
        @Override
        public void onOfferwallClosed() {
    
        }
    }
    
    

    Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.

    public class AndroidLauncher extends AndroidApplication {
    
        private Game game;
    
        @Override
        protected void onCreate (Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            game = new Game();
            game.setAdManager(new AndroidAdManager(this, game));
            game.setPermissionManager(new AndroidPermissionManager(this, game));
            initialize(game, config);
        }
    
    
        @Override
        protected void onPause() {
            super.onPause();
            game.getAds().onPause();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            game.getAds().onResume();
        }
    }
    

    I hope this helps in your project!