How to Integrate Admob in Libgdx games for android?


It is very simple to integrate Admob Banner, Interestitial, and Reward Video ads in LIBGDX Game application, I have added the steps Admob enable in Android Platform here. Incase you are looking for IOS to enable Admob refer Official Admob in Libgdx blog .

Steps :

1. build.gradle change
2. AndroidLauncher change
3. Create 'res/layout/activity_main_game.xml'
4. Create a App.java  and AndroidManifest.xml change.
5. Update MainGame.java
6. Create GameContext.java
7. Now show add from your game screen


1. build.gradle

/build.gradle

allprojects {
    //.......
    repositories {
       //.....
        jcenter()
        google()
        maven {
            url "https://maven.google.com"
        }
    }
}

// ......
// .......

project(":android") {
    // ....
    dependencies {
        //....
        implementation 'com.google.android.gms:play-services-ads:15.0.0'
    }
}

2. AndroidLaunche.java

\android\src\your\package\name\AndroidLauncher.java


public class AndroidLauncher extends AndroidApplication implements ActionListener {


    private InterstitialAd interstitialAd;
    private RewardedVideoAd videoAd;

    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler();

        // 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);

        setContentView(R.layout.activity_main_game);


        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        config.numSamples = 2;

        //initialize(new MainGame(), config);

        MainGame mainGame = new MainGame();
        mainGame.setActionListener(this);
        View gameView = initializeForView(mainGame, config);

        LinearLayout linearLayout = findViewById(R.id.container_game_board);
        linearLayout.addView(gameView);

        interstitialAd = new InterstitialAd(this);
        videoAd = MobileAds.getRewardedVideoAdInstance(this);
        interstitialAd.setAdUnitId(App.AD_INTERSTITIAL_ID);
        loadBannerAds();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadInterstitialAd();
        loadVideoAd();
    }

    private void loadVideoAd() {
        videoAd.loadAd(App.AD_VIDEO_ID, new AdRequest.Builder().build());
    }

    private void loadInterstitialAd() {
        interstitialAd.loadAd(new AdRequest.Builder().build());
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }


    @Override
    public void onAction(int action, Object data) {
        switch (action) {
            case ACTION_SHOW_INTERESTITIAL_ADS: {
                handler.post(() -> {
                    if (interstitialAd.isLoaded()) {
                        interstitialAd.show();
                    } else if (videoAd.isLoaded()) {
                        videoAd.show();
                    } else {
                        Log.d("TAG", "Fullscreen ads not loaded yet.");
                    }

                });

                break;
            }
            case ACTION_SHOW_VIDEO_ADS: {
                handler.post(() -> {
                    if (videoAd.isLoaded()) {
                        videoAd.show();
                    } else if (interstitialAd.isLoaded()) {
                        interstitialAd.show();
                    } else {
                        Log.d("TAG", "Fullscreen ads not loaded yet.");
                    }
                });
                break;
            }
        }
    }

    @Override
    public void setActionListener(ActionListener actionListener) {

    }


    private void loadBannerAds() {
        LinearLayout adContainer = (LinearLayout) findViewById(R.id.container_ads);
        AdView adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(App.AD_BANNER_ID);

        adContainer.addView(adView);

        Bundle extras = new Bundle();
        extras.putBoolean("is_designed_for_families", true);

        AdRequest adRequest = new AdRequest.Builder()
                // .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                // .tagForChildDirectedTreatment(true)
                .build();


//  if (BuildConfig.DEBUG) {
//   adContainer.setVisibility(View.GONE);
//  } else {
//   adContainer.setVisibility(View.VISIBLE);
//  }

        adView.loadAd(adRequest);

    }


}

3. activity_main_game.xml

\android\res\layout\activity_main_game.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/container_game_board"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#37474f"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/container_ads"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:orientation="vertical">

        </LinearLayout>
    </LinearLayout>


</RelativeLayout>

4.App.java

\android\src\your\package\name\App.java
public class App extends Application {
    public static final String TAG = "App";
    public static final Boolean DEBUG = true;

    public static final String AD_APP_ID = "ca-app-pub-43293525111485162870~141719551627";
    public static final String AD_BANNER_ID = "ca-app-pub-43293551148562870/357121990458";
    public static final String AD_INTERSTITIAL_ID = "ca-app-pub-4323931551485628170/220411423689";
    public static final String AD_VIDEO_ID = "ca-app-pub-43293551485162870/961997170328";
    public static final String AD_NATIVE_ID = "ca-app-pub-432935151481562870/25514801109";

    @Override
    public void onCreate() {
        super.onCreate();
        MobileAds.initialize(getApplicationContext(), App.AD_APP_ID);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }


}

4.1. AndroidManifest.xml


 <!-- ........ -->

<uses-permission android:name="android.permission.INTERNET" />

<application
         <!-- ........ -->
        android:name=".App"  >
      <!-- ........ -->

</application>



5. ApplicationListener.java

\core\src\your\package\name\ActionListener.java

public interface ActionListener {
    public int ACTION_DEFAULT = 1000; // Default action for sample

    public int ACTION_SHOW_INTERESTITIAL_ADS = 1;
    public int ACTION_SHOW_VIDEO_ADS = 2;

    public void onAction(int action, Object data);

    public void setActionListener(ActionListener actionListener);
}

6. MainGame.java

\core\src\your\package\name\MainGame.java


public class MainGame extends Game implements ActionListener {
    public SpriteBatch batch;
    public Holder holder;
    public Context context;

    public class Context {
        public SpriteBatch batch;
        public MainGame mainGame;

        public ActionListener actionListener;
    }


    public MainGame() {
        context = new Context();
    }

    @Override
    public void create() {
        batch = new SpriteBatch();

        context.batch = this.batch;
        context.mainGame = this;

        holder = new Holder();
        holder.setArrayData();

        if (Gdx.app.getPreferences("data.xml").get().isEmpty()) {
            holder.createDataDefault();
        }

        setScreen(new HomeScreen(context));
    }

    @Override
    public void render() {
        super.render();
    }

    @Override
    public void dispose() {
        super.dispose();
        batch.dispose();

    }

    @Override
    public void onAction(int action, Object data) {

    }

    @Override
    public void setActionListener(ActionListener actionListener) {
        context.actionListener = actionListener;
    }
}

7. Show Ads in GameScreen.java

\core\src\your\package\name\Screens\GameScreen.java

public class GameScreen extends Screen {


//.........
// Call following two function when you want to display full screen ads


    private void showVideoAd() {
        if (context.actionListener != null) {
            context.actionListener.onAction(ActionListener.ACTION_SHOW_VIDEO_ADS, null);
        }
    }

    private void showInterestialAd() {
        if (context.actionListener != null) {
            context.actionListener.onAction(ActionListener.ACTION_SHOW_INTERESTITIAL_ADS, null);
        }
    }
}

Comments