Adding Google Admob Ads to Android App (Banner and Interstitial ads)





5.00/5 (4 votes)
Adding Google Admob Ads to Android App (Banner and Interstitial ads). Google AdMob is the most popular mobile ads platform used by app developers worldwide. Integrating AdMob to your app allows you to monetize your app and earn on the basis of Impressions and clicks on ads in your app.
Google’s AdMob is the most popular mobile ads platform used by app developers worldwide. Integrating AdMob to your app allows you to monetize your app and earn on the basis of Impressions and clicks on ads in your app. AdMob provides you tools to analyze, understand and track your audience through integration with google analytics.
It has a very flexible ad control and allows you to choose between a variety of types and sizes of the apps which can help to increase your earning through app advertising. Admob also has support for in-app purchase ads to increase the number of in-app transactions from your users.
Admob is available for Android, iOS, Unity and Cocos platform. We will be discussing the Banner and Interstitial versions of Ads which are very popular across all the ad platform.
Admob Banner vs Interstitial ads
Banners Ads are small ads which are usually displayed at the top or bottom of the screen as shown int the figure below. Standard android admob banner size is 320×50 although other sizes are also available. Banner Ads are very popular with mobile developers since they don’t interfere much with the user experience and cover very small part of the screen. However they have a low engagement rates.
Interstitials Ads are bigger full-screen ads. They block the screen for some time until the user presses a “x” button to close the Ad. By blocking the complete screen interstitial Ads compel the user to interact with the ad, giving high user engagement and conversion rates. However these Ads if not added at proper places will often lead to frustrating user experience. Below is an example of interstitial ad.
In this tutorial we will discuss admob integration on android using an example App. We will be creating a dummy game app consisting of two levels. Level One will show the Banner Ads and when the user clicks on the LevelTwo an Interstitial Ad will be loaded and the user will be taken to Level Two once the Ad is closed.
Before starting the discussion, please note the following:
Clicking on your own Ads to earn money is strictly against the Google AdMob’s policy, You must use the test Ads while the app is in devlopment, even if you want to test for live ads before launching your app, avoid clicking on them otherwise your Admob account might get suspended.
Pre-requisites
- Android Studio installed on your PC (Unix or Windows).
- A real time android device (Smartphone or Tablet) configured with Android Studio.
Creating a New Android Studio Project
- Open Android Studio and create a new project by clicking on File -> New -> New Project.
- Enter project name, we have used GameApp and company domain application.example.com (We have used our company domain i.e androidtutorialpoint.com. Similarly you can use yours).
- Click Next and choose appropriate android version.
- Click Next and select an Empty Activity.
- Choose activity name, we have named the activity as
LevelOneActivity
. Also make sure generate layout checkbox is checked.
This will create new android studio project. Now you are ready to montetize your new Game App.
Create your Ad Units
- Go to Google Admob Page and Sign-Up if you don’t have an existing account. Just Sign-In in case you already have a Google Admob Account.
- Click on Monetize Tab
- Click on Montetize New App button.
- Select an App. You have three Options as shown in the fig below.
- You can search your app, incase you are adding admob to an existing app.
- Add App Manually allows to add a new app by giving a package name.
- Select a previously added app, if you have already added the app but didn’t follow the complete process to add admob ads.
- Enter your app name, select the platform as Android and click on Add app button.
- Select ad format and name the ad unit.
Since we are adding both the banner and interstitial ads we have to make two entries one for each type of ads and save them. You can choose other options as per your requirement. We are retaining the default options.
- On saving the Ad unit you will get Ad unit name and Ad unit ID as shown in the figure below. Note the Ad unit ID for the two Ad units you have just created. Later we have to put these ID’s in your apps strings.xml file.
Add Banner and Interstitial adds to your Project
- Add the following dependency in your app’s build.gradle file to use the Google Admob SDK in your project.
build.gradle
compile 'com.google.android.gms:play-services-ads:8.4.0'
- Add the Ad ID for the Ad Units created earlier in the strings.xml file.
strings.xml
<resources> <string name="app_name">GameApp</string> <string name="interstitial_ad_sample">Interstitial Ad Sample</string> <string name="level_one">Level One</string> <string name="level_two">Level Two</string> <string name="ad_id_interstitial">ca-app-pub-7744357389506091/9257560120</string> <string name="ad_id_banner">ca-app-pub-7744357389506091/6304093723</string> <string name="gameHeader">My Game App</string> </resources>
Replace the
ad_id_interstitial
andad_id_banner
with your own Ad ID’s, we have also added some other string resources which will be used in the project later. - In AndroidManifest.xml add the permissions to access Internet and Network State.
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Next, add the google play services meta data to the application tag. This embeds the version of Google Play services that the app was compiled with.
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
Also add an Ad activity to handle the config changes of your app like orientation change.
<activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
Completed AndroidManifest.xml code will be as in the following file
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidtutorialpoint.gameapp" > <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:supportsRtl="true" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name=".LevelOneActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <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>
- Open the layout file activity_level_one.xml and add the following code to it.
activity_level_one.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:ads="http://schemas.android.com/apk/res-auto" 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=".LevelOneActivity"> <TextView android:id="@+id/game_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="@string/gameHeader" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/level_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/game_text_view" android:layout_centerHorizontal="true" android:text="@string/level_one" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/level_two_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/level_two" /> <!-- view for AdMob Banner Ad --> <com.google.android.gms.ads.AdView android:id="@+id/banner_AdView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" ads:adSize="BANNER" ads:adUnitId="@string/ad_id_banner" /> </RelativeLayout>
Here we are using a Relative Layout as a parent layout. We have a
TextView
to display a static message “My Game App”, Next we have aTextView
to display the current level of the game. We only have two Levels – Level One and Level Two.Then we have a button that will take us to Level Two. At the end we have a Google Admob Adview which will be used to display the Banner Ads at the bottom of the your app Screen as discussed in starting. We have added the adUnitId for the banner Ad using our ad_id_banner string resource. For Banner Ads adSize has a value of Banner.
- Open
LevelOneActivity.java
and create private variables for the Level TwoButton
,InterstitialAd
, LevelTextView
and also the BannerAdView
.LevelOneActivity.java
private Button mLevelTwoButton; private InterstitialAd mInterstitialAd; private TextView mLevelTextView; private AdView mBannerAd;
In the
onCreate()
method ofLevelOneActivity
intialize add the reference to the buttons and views. Also add anOnClickListener()
for the Level Two Button and explicitly enable it on start of the activity.// Create the next level button, which tries to show an interstitial when clicked. mLevelTwoButton = ((Button) findViewById(R.id.level_two_button)); // Load the add into Admob banner view. mBannerAd = (AdView) findViewById(R.id.banner_AdView); // Text view to show the level number. mLevelTextView = (TextView) findViewById(R.id.level_text_view); mLevelTwoButton.setEnabled(true); mLevelTwoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showIntAdd(); } });
Next Create and Load a new Interstitial Ad and then load Banner Ads. For now just put the following methods in
onCreate()
method of theLevelOneActivity.java
, we will be explaining these methods next.// Creating and load a new InterstitialAd . mInterstitialAd = createNewIntAd(); loadIntAdd(); //Load BannerAd showBannerAd();
The
showBannerAd()
method builds a new adRequest using theAdRequest.Builder()
method and then the request is loaded to the Banner AdView we added to the layout File, Please note the use ofaddTestDevice(“754DB6521943676637AE86202C5ACE52”)
method in the method. As we have discussed in the beginning the app developer should not click on his own live ads. To prevent your Admob account from being suspended you should always work with the test ads. When you run your the LogCat output will show you theTestDeviceId
for your device as shown in the figure below.Replace the
TestDeviceId
in theshowBannerAd()
method with your own device Id.Be sure to remove the
TestDeviceId
before going live with your app.Add the following methods after
onCreate()
method of theLevelOneActivity.java
.private void showBannerAd() { AdRequest adRequest = new AdRequest.Builder() .addTestDevice("754DB6521943676637AE86202C5ACE52") .build(); mBannerAd.loadAd(adRequest); }
Also add
createNewIntAd()
method after theshowBannerAd()
, This method creates a new Interstitial Ad and also sets theAdUnitId
andsetAdListener
property of the new Interstitial Ad. In the AdListener we have are enabling theLevelTwoButon
once the Ad is loaded and also in the case that Ad fails to load. Once the user closes the Ad the Game proceeds to level two by calling the functionlevelTwo()
.private InterstitialAd createNewIntAd() { InterstitialAd intAd = new InterstitialAd(this); // set the adUnitId (defined in values/strings.xml) intAd.setAdUnitId(getString(R.string.ad_id_interstitial)); intAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { mLevelTwoButton.setEnabled(true); } @Override public void onAdFailedToLoad(int errorCode) { mLevelTwoButton.setEnabled(true); } @Override public void onAdClosed() { // Proceed to the next level. levelTwo(); } }); return intAd; }
Next, Add the following code in
LevelOneActivity
after the above methods. TheshowIntAdd()
checks whether the add has been loaded and if it is available then it displays the Ad otherwise it displays the next level of the game. TheloadIntAdd()
will disable the level two button and then create a newadRequest
similar toshowBannerAd()
method and then loads the request in the AdView. ThelevelTwo()
invokes the second level of our game, here we are just making the button disappear and changing the level text to display Level Two.private void showIntAdd() { // Show the ad if it's ready. Otherwise toast and reload the ad. if (mInterstitialAd != null && mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } else { levelTwo(); } } private void loadIntAdd() { // Disable the level two button and load the ad. mLevelTwoButton.setEnabled(false); AdRequest adRequest = new AdRequest.Builder() .addTestDevice("754DB6521943676637AE86202C5ACE52") .build(); mInterstitialAd.loadAd(adRequest); } private void levelTwo() { // Show the next level mLevelTwoButton.setVisibility(View.INVISIBLE); mLevelTextView.setText("Level Two"); Toast t = Toast.makeText(this,"You have reached Level Two !!",Toast.LENGTH_LONG); t.show(); }
Now, run the app on your phone or emulator and you should see Banner Ad at the bottom of the screen and Interstitial Ad on clicking Level Two Button.