All CategoriesAndroid App Development

Google Admob with Banner and Interstitial Ads in Android Apps

This Blog is in continuation with our previous blog “Beginner’s Guide to AdMob – a Portmanteau for “Advertising on Mobile” where we talked all about AdMob and how to monetize your App with Ads. Here we will go a step forward and talk about how to actually write code for the App to create AdMob in it.

Below we will be discussing the code: AdMob

Create a Sample Application for Two Types of AdMob about Banner Ad and Interstitial Ad. First we will talk about Banner Ad.

Banner Ad App:

  1. First of all add the code for Google Ad services in build.gradle file In dependencies:
compile 'com.google.android.gms:play-services:7.0.0'

2. In the manifest file i.e AndroidManifest.xml add below code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gms.example.bannerexample" >
    <!-- 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="@drawable/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"/>
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <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>

3. Add your banner Ad unit ID to string.xml file:

<!-- This is an ad unit ID for a test ad. Replace with your own banner ad unit id. -->
    <string name="banner_ad_uncait_id">-app-pub-3940256099942544/6300978111</string>

Note: This banner ID key is for my Ad. Since you have already learn how to generate banner ID key, create a new Ad ID for your app.
 
4. Add below code to MainActivity.java

package com.google.android.gms.example.bannerexample;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class MyActivity extends AppCompatActivity {
    private AdView mAdView;
    private WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
         mAdView = (AdView) findViewById(R.id.ad_view);
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();
        mAdView.loadAd(adRequest);
        webview = (WebView) findViewById(R.id.webView);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl(" https://acadgild.com/blog/category/android/");
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }
    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }
}

5. Add this code to design your ad in “activity_main.xml” file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">
    <com.google.android.gms.ads.AdView
        android:id="@+id/ad_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />
    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/ad_view"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Run the code and you will see the output as shown in figure below:

With this we have successfully learnt how to create and display Ad at the bottom of the page. Now we will see how to create an Interstitial Ad in the App.

Interstitial Ad App

1. First of all add the code for Google Ad services in build.gradle file In dependencies

compile 'com.google.android.gms:play-services:7.0.0'

2. In the manifest file i.e AndroidManifest.xml add below code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gms.example.interstitialexample" >
    <!-- 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="@drawable/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=".MyActivity"
            android:label="@string/app_name" >
            <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>

3. Add this code to design your ad in “activity_main.xml” file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">
    <TextView
        android:id="@+id/game_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="@string/impossible_game"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/game_title"
        android:layout_centerHorizontal="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/retry_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Retry" />
</RelativeLayout>

4. Add below code to MainActivity.java

package com.google.android.gms.example.interstitialexample;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class MyActivity extends ActionBarActivity {
    private static final long GAME_LENGTH_MILLISECONDS = 3000;
    private InterstitialAd mInterstitialAd;
    private CountDownTimer mCountDownTimer;
    private Button mRetryButton;
    private boolean mGameIsInProgress;
    private long mTimerMilliseconds;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        // Create the InterstitialAd and set the adUnitId.
        mInterstitialAd = new InterstitialAd(this);
        // Defined in res/values/strings.xml
        mInterstitialAd.setAdUnitId(getString(R.string.ad_unit_id));
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                startGame();
            }
        });
        mRetryButton = ((Button) findViewById(R.id.retry_button));
        mRetryButton.setVisibility(View.INVISIBLE);
        mRetryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInterstitial();
            }
        });
        startGame();
    }
    private void createTimer(final long milliseconds) {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        final TextView textView = ((TextView) findViewById(R.id.timer));
        mCountDownTimer = new CountDownTimer(milliseconds, 50) {
            @Override
            public void onTick(long millisUnitFinished) {
                mTimerMilliseconds = millisUnitFinished;
                textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1));
            }
            @Override
            public void onFinish() {
                mGameIsInProgress = false;
                textView.setText("done!");
                mRetryButton.setVisibility(View.VISIBLE);
            }
        };
    }
    @Override
    public void onResume() {
        // Start or resume the game.
        super.onResume();
        if (mGameIsInProgress) {
            resumeGame(mTimerMilliseconds);
        }
    }
    @Override
    public void onPause() {
        // Cancel the timer if the game is paused
        mCountDownTimer.cancel();
        super.onPause();
    }
    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and restart the game.
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        } else {
            Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
            startGame();
        }
    }
    private void startGame() {
        if (!mInterstitialAd.isLoaded() && !mInterstitialAd.isLoaded()) {
            AdRequest adRequest = new AdRequest.Builder().build();
            mInterstitialAd.loadAd(adRequest);
        }
        mRetryButton.setVisibility(View.INVISIBLE);
        resumeGame(GAME_LENGTH_MILLISECONDS);
    }
    private void resumeGame(long milliseconds) {
        mGameIsInProgress = true;
        mTimerMilliseconds = milliseconds;
        createTimer(milliseconds);
        mCountDownTimer.start();
}
}

Run this code and you will get an output as shown in figure below:
Hope with these two blogs you now have a clear idea on how to create Ad in your App using AdMob.
Keep visiting our website Acadgild for more updates on Big Data and other technologies. Click here to learn Android App Development.

Android Programming

2 Comments

  1. Hi.. How to hide adsense ads in android webview but not mobile or desktop browser?
    Recently I hired a developer to make a Webview App of my wordpress website.
    I am using Adsense on my website. Now I would like to use Admob on my App.
    I can see google adsense ads on my Webview App. How can I stop adsense on webview android app?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close