Making a successful app or game is difficult and earning money from your mobile game or app is also difficult, there are many ways to earn money from your app or game such as :
Advertising is one of the best ways to earn revenue from all the users who are using your app and having an active internet connection. Most of the Apps on google play store and apple app store are using advertising to monetize their game or app. In this tutorial, we will learn how to integrate Ads in our android app so that you can earn a decent amount of income from your app. In many Android Apps(Learn Android App development) or games, we have seen the different types of ads formats with different sizes and positions such as:
-
Banner Ad
-
Interstitial Ad
-
Native Ad
-
Rewarded Ad
In this tutorial, we will integrate the Google Admob SDK to show Banner Ads in our Android app, so that we can earn some revenue from our app or games.
Features of Google Admob
-
Easy integration
-
High-quality ads
-
High eCPM ( Effective Cost Per Mille )
-
Different Ad Formats as we saw above
-
Minimum payout of $100 via wire transfer
-
Good fill rate
-
Support Android and IOS
-
SDKs for different software such as Unity3d, android studio, etc
-
Provide test ads to test the integration
Banner Ads:
Banner ads are a small rectangular ad which occupies little space in our app layout, mainly show at the top or bottom of the user device screen
Some Feature of Banner Ad:
-
It can be shown at any place such as the top of the screen, the bottom of the screen, or inside the vertical scrolling content such as listview, recycler view, or simple scrollView
-
Show both text ads, video ads, image ads
-
Refresh automatically in few minutes or you can change the refresh rate value in the AdMob dashboard
-
User can easily interact with the app while it is showing at the top or bottom
-
The eCPM is moderate
-
support different sizes (Banner, Large Banner, Medium Rectangle, Adaptive Banner, Smart Banner)
-
support both Mobile phones and Tablets
-
Due to its small size, it is less disturbing as compared to other formats
So let's implement a simple Admob Banner Ad in our android app.
Step 1: Create a new Project
-
Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to set up Android Studio and create your first Android project)
-
Choose "Empty Activity" from the project template window and click Next
-
Enter the App Name, Package name, save location, language(Java/Kotlin, we use Java for this tutorial ), and minimum SDK(we are using API 19: Android 4.4 which is KitKat)
-
Next click on the Finish button after filling in the above details.
-
Now, wait for the project to finish building.
Step 2: Adding the Mobile Ads SDK
To show the ads in our app we have to first implement the Admob SDK in our app, to do so
Go to Gradle Scripts->build.gradle (Module: app) section and import below dependencies and click the "Sync Now" button shown at the top:
dependencies {
// adding Admob SDK
implementation 'com.google.android.gms:play-services-ads:19.4.0'
}
Now our build.gradle file will look like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.studytonight.project"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// adding Admob SDK
implementation 'com.google.android.gms:play-services-ads:19.4.0'
}
Step 3: Modify AndroidManifest.xml
Go to App -> Manifests -> AndroidManifest.xml file and add the internet permission to the Android Manifest file of your Android app:
<manifest>
<uses-permission android:name= "android.permission.INTERNET"/>
</manifest>
Now we will add our AdMob AppId to the AndroidManifest file by adding the <meta-data>
tag inside the <application>
tag:
<manifest>
<application>
<meta-data
android:name= "com.google.android.gms.ads.APPLICATION_ID"
android:value= "ca-app-pub-3940256099942544~3347511713"/>
</application>
</manifest>
To show video ads inside the banner ad views, hardware acceleration must be turned on. In Android the hardware acceleration is enabled by default, we can also enable and disable it for the entire or for each activity separately in our android manifest file as show below:
<!-- for the entire app -->
<application
android:hardwareAccelerated="true">
</application>
and for individual activity:
<!-- for the each activity -->
<application>
<activity
android:hardwareAccelerated="true"> </activity>
</application>
The complete code of the AndroidManifest.xml file is shown below:
<?xml version= "1.0" encoding= "utf-8"?>
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
package= "com.studytonight.project">
<!-- adding internet permission to show allow app to use internet to load and show ads -->
<uses-permission android:name= "android.permission.INTERNET"/>
<!-- hardware Acceleration is turned on for the entire app -->
<application
android:hardwareAccelerated= "true"
android:allowBackup= "true"
android:icon= "@mipmap/ic_launcher"
android:label= "@string/app_name"
android:roundIcon= "@mipmap/ic_launcher_round"
android:supportsRtl= "true"
android:theme= "@style/AppTheme">
<activity
android:screenOrientation="portrait"
android:name= ".MainActivity">
<intent-filter>
<action android:name= "android.intent.action.MAIN" />
<category android:name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Adding AdMob App Id -->
<meta-data
android:name= "com.google.android.gms.ads.APPLICATION_ID"
android:value= "ca-app-pub-3940256099942544~3347511713"/>
</application>
</manifest>
Step 4: Modify activity_main.xml
To show a banner ad in our app we will add the AdView in our layout as shown below:
<!-- Banner AdView -->
<com.google.android.gms.ads.AdView
xmlns:ads= "http://schemas.android.com/apk/res-auto"
android:layout_alignParentBottom= "true"
ads:adUnitId= "ca-app-pub-3940256099942544/6300978111"
android:visibility= "gone"
android:id= "@+id/bannerAdView"
ads:adSize= "BANNER"
android:layout_width= "match_parent"
android:layout_height= "wrap_content">
</com.google.android.gms.ads.AdView>
We are currently showing the banner at the bottom of our screen, if you want you can change the position of the banner according to your needs
Now we will create 3 Buttons to load, show and hide the banner ad inside a vertical linear layout to show how you can control the ads programmatically in your code.
Here is the complete code of activity_main.xml after adding 3 new buttons:
<?xml version= "1.0" encoding= "utf-8"?>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:app= "http://schemas.android.com/apk/res-auto"
xmlns:tools= "http://schemas.android.com/tools"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
tools:context= ".MainActivity">
<!-- Banner AdView -->
<com.google.android.gms.ads.AdView
xmlns:ads= "http://schemas.android.com/apk/res-auto"
android:layout_alignParentBottom= "true"
ads:adUnitId= "ca-app-pub-3940256099942544/6300978111"
android:visibility= "gone"
android:id= "@+id/bannerAdView"
ads:adSize= "BANNER"
android:layout_width= "match_parent"
android:layout_height= "wrap_content">
</com.google.android.gms.ads.AdView>
<!-- vertical linear layout contain 3 button -->
<LinearLayout
android:layout_centerInParent= "true"
android:layout_margin= "16dp"
android:orientation= "vertical"
android:layout_width= "match_parent"
android:layout_height= "wrap_content">
<!-- Simple Buttons to Load Ad when clicked -->
<Button
android:textSize= "24dp"
android:layout_margin= "16dp"
android:id= "@+id/loadBannerBtn"
android:text= "Load Banner Ad"
android:fontFamily= "monospace"
android:textStyle= "bold"
android:textColor= "#ffffff"
android:background= "@color/colorPrimary"
android:layout_width= "match_parent"
android:layout_height= "60dp"/>
<!-- Simple Buttons to Show Ad when clicked -->
<Button
android:textSize= "24dp"
android:layout_margin= "16dp"
android:id= "@+id/showBannerBtn"
android:text= "Show Banner Ad"
android:fontFamily= "monospace"
android:textStyle= "bold"
android:textColor= "#ffffff"
android:background= "@color/colorPrimary"
android:layout_width= "match_parent"
android:layout_height= "60dp"/>
<!-- Simple Buttons to Hide Ad when clicked -->
<Button
android:textSize= "24dp"
android:layout_margin= "16dp"
android:id= "@+id/hideBannerBtn"
android:text= "Hide Banner Ad"
android:fontFamily= "monospace"
android:textStyle= "bold"
android:textColor= "#ffffff"
android:background= "@color/colorPrimary"
android:layout_width= "match_parent"
android:layout_height= "60dp"/>
</LinearLayout>
</RelativeLayout>
Step 5: Changes in MainActivity.java file
First, we have to import the library inside the ActivityMain.java
//libaray for Button, View and Toast
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
// important library for Google adMob
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.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
Now inside the MainActivity class, we create an object of AdView and Button and then create a boolean variable:
//Creating object of AdView
private AdView bannerAdView;
//creating Object of Button
private Button loadAdBtn;
private Button showAdBtn;
private Button hideAdBtn;
//Simple boolean for checking if ad is loaded or not
private boolean adLoaded=false;
Now inside the onCreate
we will initialize the MobileAds and will show a simple toast message when initialization is completed using the below code:
//initializing the Google Admob SDK
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
//Showing a simple Toast Message to the user when The Google AdMob Sdk Initialization is Completed
Toast.makeText (MainActivity.this, "AdMob Sdk Initialize "+ initializationStatus.toString(), Toast.LENGTH_LONG).show();
}
});
Next, we will initialize the object inside the onCreate
after initializing the SDK:
// Initializing the AdView object
bannerAdView = (AdView) findViewById(R.id.bannerAdView);
// Initializing the Button objects to their respective views from activity_main.xml file
loadAdBtn = (Button) findViewById(R.id.loadBannerBtn);
showAdBtn = (Button) findViewById(R.id.showBannerBtn);
hideAdBtn = (Button) findViewById(R.id.hideBannerBtn);
Now we will create a simple method to load the Banner Ad inside MainActivity class as shown below:
private void loadBannerAd()
{
// Creating a Ad Request
AdRequest adRequest = new AdRequest.Builder().build();
// load Ad with the Request
bannerAdView.loadAd(adRequest);
// Showing a simple Toast message to user when an ad is Loading
Toast.makeText (MainActivity.this, "Banner Ad is loading ", Toast.LENGTH_LONG).show();
}
Next, we create two more methods to show the Banner Ad and Hide the Banner Ad inside MainActivity class as shown below:
private void showBannerAd()
{
if ( adLoaded )
{
//showing the ad Banner Ad if it is loaded
bannerAdView.setVisibility(View.VISIBLE);
// Showing a simple Toast message to user when an banner ad is shown to the user
Toast.makeText (MainActivity.this, "Banner Ad Shown", Toast.LENGTH_LONG).show();
}
else
{
//Load the banner ad if it is not loaded
loadBannerAd();
// Showing a simple Toast message to user when an ad is not loaded
Toast.makeText (MainActivity.this, "Banner Ad is Loaded ", Toast.LENGTH_LONG).show();
}
}
private void hideBannerAd()
{
// Hiding the Banner
bannerAdView.setVisibility(View.GONE);
}
Now we create a click listener inside the onCreate
method so that the above functions are executed when the buttons are clicked, which we have created in the activity_main.xml file:
loadAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the loadBannerAd method
loadBannerAd();
}
});
showAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the showBannerAd method
showBannerAd();
}
});
hideAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the hideBannerAd method
hideBannerAd();
}
});
To know the stats of the Banner ad we will add the AdListener
to our bannerAdView
inside onCreate
method and will change the value of as adLoaded
, by setting it true if onAdLoaded()
method is invoked and setting it to false if onAdFailedToLoad()
is invoked as shown below in the code:
// creating different AdListener for Banner Ad with some Override methods
bannerAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// setting adLoaded to true
adLoaded=true;
// Showing a simple Toast message to user when an ad is loaded
Toast.makeText (MainActivity.this, "Ad is Loaded", Toast.LENGTH_LONG).show();
}
@Override
public void onAdFailedToLoad(LoadAdError adError) {
// setting adLoaded to false
adLoaded=false;
// Showing a simple Toast message to user when and ad is failed to load
Toast.makeText (MainActivity.this, "Ad Failed to Load ", Toast.LENGTH_LONG).show();
}
@Override
public void onAdOpened() {
// Showing a simple Toast message to user when an ad opens and overlay and covers the device screen
Toast.makeText (MainActivity.this, "Ad Opened", Toast.LENGTH_LONG).show();
}
@Override
public void onAdClicked() {
// Showing a simple Toast message to user when a user clicked the ad
Toast.makeText (MainActivity.this, "Ad Clicked", Toast.LENGTH_LONG).show();
}
@Override
public void onAdLeftApplication() {
// Showing a simple Toast message to user when the user left the application
Toast.makeText (MainActivity.this, "Ad Left the Application", Toast.LENGTH_LONG).show();
}
@Override
public void onAdClosed() {
// Showing a simple Toast message to user when the user interacted with ad and got the other app and then return to the app again
Toast.makeText (MainActivity.this, "Ad is Closed", Toast.LENGTH_LONG).show();
}
});
Overridable methods of AdListener
Here is a list of overridable methods of AdListener
:
public void onAdLoaded() |
The onAdLoaded the method is executed when an ad is loaded. We can update the UI or do other stuff when the ad is loaded.
|
public void onAdFailedToLoad(LoadAdError adError) |
The onAdFailedToLoad the method is the only one that includes a parameter. The adError parameter is of type LoadAdError describes which type of error has occurred.
|
public void onAdOpened() |
The onAdOpened() the method is executed when the user clicks on the banner ad and the ad is opened. |
public void onAdClicked() |
The onAdClicked() the method is executed when the user clicks on the banner ad.
|
public void onAdLeftApplication() |
This method is executed after onAdOpened() , when a user clicks to open another app(such as click the ad to install the game or app ), pausing the currently running app to the background.
|
public void onAdClosed() |
When the user returns back to the app after viewing an Ad or play store for installing an app or game, onAdClosed() the method is executed.
|
The Completed Code of MainActivity.java is shown below
package com.studytonight.project;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
//libaray for Button, View and Toast
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
// important library for Google adMob
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.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
public class MainActivity extends AppCompatActivity {
//Creating object of AdView
private AdView bannerAdView;
//creating Object of Buttons
private Button loadAdBtn;
private Button showAdBtn;
private Button hideAdBtn;
//Simple boolean for checking if ad is loaded or not
private boolean adLoaded=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing the Google Admob SDK
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
//Showing a simple Toast Message to the user when The Google AdMob Sdk Initialization is Completed
Toast.makeText (MainActivity.this, "AdMob Sdk Initialize "+ initializationStatus.toString(), Toast.LENGTH_LONG).show();
}
});
// Initializing the AdView object
bannerAdView = (AdView) findViewById(R.id.bannerAdView);
// Initializing the Button objects to their respective views from activity_main.xml file
loadAdBtn = (Button) findViewById(R.id.loadBannerBtn);
showAdBtn = (Button) findViewById(R.id.showBannerBtn);
hideAdBtn = (Button) findViewById(R.id.hideBannerBtn);
loadAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the loadBannerAd method
loadBannerAd();
}
});
showAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the showBannerAd method
showBannerAd();
}
});
hideAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the hideBannerAd method
hideBannerAd();
}
});
// creating different AdListener for Banner Ad with some Override methods
bannerAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// setting adLoaded to true
adLoaded=true;
// Showing a simple Toast message to user when an ad is loaded
Toast.makeText (MainActivity.this, "Ad is Loaded", Toast.LENGTH_LONG).show();
}
@Override
public void onAdFailedToLoad(LoadAdError adError) {
// setting adLoaded to false
adLoaded=false;
// Showing a simple Toast message to user when and ad is failed to load
Toast.makeText (MainActivity.this, "Ad Failed to Load ", Toast.LENGTH_LONG).show();
}
@Override
public void onAdOpened() {
// Showing a simple Toast message to user when an ad opens and overlay and covers the device screen
Toast.makeText (MainActivity.this, "Ad Opened", Toast.LENGTH_LONG).show();
}
@Override
public void onAdClicked() {
// Showing a simple Toast message to user when a user clicked the ad
Toast.makeText (MainActivity.this, "Ad Clicked", Toast.LENGTH_LONG).show();
}
@Override
public void onAdLeftApplication() {
// Showing a simple Toast message to user when the user left the application
Toast.makeText (MainActivity.this, "Ad Left the Application", Toast.LENGTH_LONG).show();
}
@Override
public void onAdClosed() {
// Showing a simple Toast message to user when the user interacted with ad and got the other app and then return to the app again
Toast.makeText (MainActivity.this, "Ad is Closed", Toast.LENGTH_LONG).show();
}
});
}
private void loadBannerAd()
{
// Creating a Ad Request
AdRequest adRequest = new AdRequest.Builder().build();
// load Ad with the Request
bannerAdView.loadAd(adRequest);
// Showing a simple Toast message to user when an ad is Loading
Toast.makeText (MainActivity.this, "Banner Ad is loading ", Toast.LENGTH_LONG).show();
}
private void showBannerAd()
{
if ( adLoaded )
{
//showing the ad Banner Ad if it is loaded
bannerAdView.setVisibility(View.VISIBLE);
// Showing a simple Toast message to user when an banner ad is shown to the user
Toast.makeText (MainActivity.this, "Banner Ad Shown", Toast.LENGTH_LONG).show();
}
else
{
//Load the banner ad if it is not loaded
loadBannerAd();
// Showing a simple Toast message to user when an ad is not loaded
Toast.makeText (MainActivity.this, "Banner Ad is Loaded ", Toast.LENGTH_LONG).show();
}
}
private void hideBannerAd()
{
// Hiding the Banner
bannerAdView.setVisibility(View.GONE);
}
}
Now we have completed the integration of the Google Admob Banner Ad in our Android App. We can customize the size of our banner ad using the following sizes shown below.
Different Banner Sizes supported by AdMob in Tablets and Mobile Phones:
Size in dp |
Description |
Availability |
AdSize constant |
320x50 |
Banner |
Mobile Phones and Tablets |
BANNER |
320x100 |
Large Banner |
Mobile Phones and Tablets |
LARGE_BANNER |
300x250 |
IAB Medium Rectangle |
Mobile Phones and Tablets |
MEDIUM_RECTANGLE |
468x60 |
IAB Full-Size Banner |
Tablets |
FULL_BANNER |
728x90 |
IAB Leaderboard |
Tablets |
LEADERBOARD |
width x Adaptive height |
Adaptive banner |
Mobile Phones and Tablets |
No AdSize Constant |
Screen width x 32|50|90 |
Smart banner |
Mobile Phones and Tablets |
SMART_BANNER |
Output:
In the below snapshots, you can see how the Banner Ad will look in the android application.
Banner Ad at the bottom of the mobile phone screen:
Banner Ad at the top of the mobile phone screen:
LARGE_BANNER Ad at the bottom of the mobile phone screen:
LARGE_BANNER Ad at the top of the mobile phone screen:
MEDIUM_RECTANGLE Banner Ad at the bottom of the mobile phone screen:
MEDIUM_RECTANGLE Banner Ad at the top of the mobile phone screen:
Conclusion:
In just 5 simple steps we have integrated shown yous the basic example for creating a Google Admob Banner Ad. If you face any issue while doing this, please share it in the comment section below and we will be happy to help.
You may also like: