Android Studio Admob Banner And Interstitial Tutorial

Android Studio Admob Interstitial Tutorial

This tutorial will show you how to implement Admob banner and interstitial ads using Android Studio. They will help you to make some money on android. Interstitial are full screen ads and should be displayed in a natural transition point i.e. during game pause or when changing activities (i.e. before showing highscore).

Install Dependencies

Before we start let’s make sure we have all the necessary prerequisites installed and ready to be used.

Download Google Repository package from Tools > Android > SDK Manager, which contains the artifact Google Play SDK.

Android Studio Admob Banner And Interstitial Tutorial

Android Studio Admob Banner And Interstitial Tutorial

Configure Gradle

Gradle is a build system containing some great features. It will help us create a reference to google play services. Edit the file below and add com.google.android.gms:play-services:7.0.0 to the dependency section.

File: build.gradle(Module: app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.ahotbrew.admobinterstitial"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.google.android.gms:play-services:7.0.0'
}

You may get a Sync Now warning in your Android Studio after adding it. Click on the link as this will refresh your project and include the latest google play service library. Run the project and make sure it compiles without errors.

Create Ad

Start by adding the two user permissions, meta-data and adActivity as shown below.

File: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ahotbrew.admobinterstitial" >

    <!-- Include required permissions for Google Mobile Ads to run-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!--This meta-data tag is required to use Google Play Services.-->
        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--Include the AdActivity configChanges and theme. -->
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
    </application>

</manifest>

Create the layout.

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Interstitial Add"
        android:id="@+id/newgame_button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="58dp" />

</RelativeLayout>

The Admob id ca-app-pub-3940256099942544/6300978111 and ca-app-pub-3940256099942544/1033173712 are test ids. Make sure you create your own Admob ad unit and replace the ids.

In this step we will show the Interstitial add on button click and the banner on the bottom of page load.

File: MainActivity.xml

package com.ahotbrew.admobinterstitial;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends ActionBarActivity {

    InterstitialAd mInterstitialAd;
    Button mNewGameButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNewGameButton = (Button) findViewById(R.id.newgame_button);

        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

        mNewGameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    //Begin Game, continue with app
                }
            }
        });

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {

                //Begin Game, continue with app
            }
        });

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mInterstitialAd.loadAd(adRequest);
    }

}

Sit back, take a sip from your hot brew and run your project.

Don’t forget to join or newsletter and get free android tutorials to enjoy with your hot brew.

  • ahmed bik

    hi
    I have problem in android studia

    you can help me

    this code

    Ads: Ad is not visible. Not refreshing ad.
    I waited

  • Gurinder

    Hi Ahmed,

    Try using another admob test id: ca-app-pub-3940256099942544/6300978111

    Are you getting any errors in the log i.e. “Not enough space to show ad” in the log” ? If you’re getting this then It sounds like you’re testing the app on a device with a screen that’s 320dp wide. With the default padding for the activity (16dp), there’s not enough space to show a 320×50 test banner. Try removing the android:paddingRight and android:paddingLeft attributes from the RelativeLayout in activity_main.xml, and then recompiling the app.

    • ahmed bik

      thank you
      but do you can give me code …….

      this my code

  • Mritunjay Rawat

    all ads examples in this app with xml and java codes :- click
    https://play.google.com/store/apps/details?id=manu.r06.AdMobAdExamples

  • CanadianHobo

    Remember when editing the Configure Gradle, remember to check the
    version you are using because Android Studio is always updating. As of
    today, it is ‘com.google.android.gms:play-services-ads:9.6.1’