New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
CLOSE
   Android  Google AdMob  Mobile Application  
   Technology    Programming

How to add Admob Native Ad in Android App

         
 NOVEMBER 3, 2020   by onlyklohan

In this article we will learn to integrate Google Admob Native Ad in you android app, so before going to coding part we will first learn some basics and features of Native Ads. You can also learn about adding Banner Ads, Interstitial Ads and Rewarded Ads in android app from our previous tutorials.

Native Ads :

Native Ad is similar to a banner Ad but with some customizations so that it leads to a better user experience and matches the UI or theme of our app and become less disturbing to the user and hence increases the user engagement with the app and increases the revenue and it is of 2 types:

  • Small Native Ads

  • Medium Native Ads

Feature of Native Ad

  • Support frequency cap means wecan decide how many ads are show to the user daily or hourly or per minute

  • The eCPM is hight as compare to Banner Ads but less than the Interstitial Ads and Rewarded Ad, so it leads to more revenue than banner Ads

  • Support both Mobile phones and Tablets

  • Fill rate is maximum

  • We can customize the layout of the native ad so that it will fit with the ui of our app

  • Even work with low internet connection speed as the ads which are shown to the users will take less data

  • we can place the native ad any where in our app such as at the bottom, at the top or in-between the items of the recycler or list view or in a simple horizontal or vertical scroll views

So let's implement a simple Admob Native Ad in our android app.

Step 1: Create a new Project

  1. Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to setup Android Studio and create your first Android project)

  2. Choose "Empty Activity" from the project template window and click Next

  3. 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 (KitKat) )

  4. Next click on Finish button after filling the above details

  5. Now wait for the project to finish building.

Step 2: Adding the Native Templates

To add Native Templates in our app we have to follow some basic steps:

  • First we have to download the Native Templates, so got to developers.google

  • Then click on the Download Native Templates, now you will be directed to Github

  • Then download the zip file from the GitHub and extract the zip file to any folder and remember the location of the folder, we will use it later

  • Now go inside Android studio and click on File->New->Import Module, Now you will see a new window (Import Module from Source) Now click on Browse icon and select the nativetemplates folder and click on finish and wait for Gradle build to finish.

  • Now open the Gradle Scripts->build.gradle (Module: app) section and import the nativetemplates project and click the "sync Now" show at the top as shown below:

    //adding native templates
    implementation project(':nativetemplates')

  • Now our build.gradle file look like as shown below:
    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 native templates
        implementation project(':nativetemplates')
    }

Step 3: Adding the Mobile Ads SDK

To show the native ads in our app we also have to implement the Admob sdk in our app, to do so follow the below steps.

Go to Gradle Scripts->build.gradle (Module: app) section and import below dependencies and click the “sync Now” show at the top

dependencies {
     // adding Admob SDK
     implementation 'com.google.android.gms:play-services-ads:19.4.0'
}

Now our build.gradel file look like

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'
    //adding native templates
    implementation project(':nativetemplates')

}

Step 4: Modify AndroidManifest.xml

  • Go to app->manifests->AndroidManifest.xml file and add the internet permission to the Android Manifest file:
    <manifest>
    <uses-permission android:name= "android.permission.INTERNET"/> 
    </manifest>

  • Now we add add our AdMob AppId to your in 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 in the Native 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>
    <!-- for the each activity -->
    <application>
            <activity
               android:hardwareAccelerated="true"> </activity>
    </application>

  • The Complete code of 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 5: Modify activity_main.xml

We create 3 Buttons to load and show Native ad insde a vertical linearLayout:

<!-- vertical linear layout with 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 Native Ad when clicked -->
    <Button
        android:textSize= "24dp"
        android:layout_margin= "8dp"
        android:id= "@+id/loadNativeBtn"
        android:text= "Load Native  Ad"
        android:fontFamily= "serif"
        android:textStyle= "bold"
        android:textColor= "#ffffff"
        android:background= "@color/colorPrimary"
        android:layout_width= "match_parent"
        android:layout_height= "60dp"/>

    <!-- Simple Buttons to Show  Native Ad if is is loaded when clicked -->
    <Button
        android:textSize= "24dp"
        android:layout_margin= "8dp"
        android:id= "@+id/showNativeBtn"
        android:text= "Show Native  Ad"
        android:fontFamily= "serif"
        android:textStyle= "bold"
        android:textColor= "#ffffff"
        android:background= "@color/colorPrimary"
        android:layout_width= "match_parent"
        android:layout_height= "60dp"/>

    <!-- Simple Buttons to Hide  Native Ad if it is shown  -->
    <Button
        android:textSize= "24dp"
        android:layout_margin= "8dp"
        android:id= "@+id/hideNativeBtn"
        android:text= "Hide Native  Ad"
        android:fontFamily= "serif"
        android:textStyle= "bold"
        android:textColor= "#ffffff"
        android:background= "@color/colorPrimary"
        android:layout_width= "match_parent"
        android:layout_height= "60dp"/>

</LinearLayout>

Next, we add the TemplateView inside the layout as shown below:

<!-- Template View for native ad -->
    <com.google.android.ads.nativetemplates.TemplateView
        android:layout_alignParentBottom= "true"
        android:visibility= "gone"
        android:id= "@+id/nativeTemplateView"
        app:gnt_template_type= "@layout/gnt_medium_template_view"
        android:layout_width= "match_parent"
        android:layout_height= "wrap_content" />

There are 2 type of template and we can change it using the code app:gnt_template_type=

  • Small Template
    @layout/gnt_small_template_view

  • Medium Template
    @layout/gnt_medium_template_view 

The complete code of activity_main.xml is show below:

<?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">

<!-- Template View for native ad -->
    <com.google.android.ads.nativetemplates.TemplateView
        android:layout_alignParentBottom= "true"
        android:visibility= "gone"
        android:id= "@+id/nativeTemplateView"
        app:gnt_template_type= "@layout/gnt_medium_template_view"
        android:layout_width= "match_parent"
        android:layout_height= "wrap_content" />

    <!-- vertical linear layout with 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 Native Ad when clicked -->
        <Button
            android:textSize= "24dp"
            android:layout_margin= "8dp"
            android:id= "@+id/loadNativeBtn"
            android:text= "Load Native  Ad"
            android:fontFamily= "serif"
            android:textStyle= "bold"
            android:textColor= "#ffffff"
            android:background= "@color/colorPrimary"
            android:layout_width= "match_parent"
            android:layout_height= "60dp"/>

        <!-- Simple Buttons to Show  Native Ad if is is loaded when clicked -->
        <Button
            android:textSize= "24dp"
            android:layout_margin= "8dp"
            android:id= "@+id/showNativeBtn"
            android:text= "Show Native  Ad"
            android:fontFamily= "serif"
            android:textStyle= "bold"
            android:textColor= "#ffffff"
            android:background= "@color/colorPrimary"
            android:layout_width= "match_parent"
            android:layout_height= "60dp"/>

        <!-- Simple Buttons to Hide  Native Ad if it is shown  -->
        <Button
            android:textSize= "24dp"
            android:layout_margin= "8dp"
            android:id= "@+id/hideNativeBtn"
            android:text= "Hide Native  Ad"
            android:fontFamily= "serif"
            android:textStyle= "bold"
            android:textColor= "#ffffff"
            android:background= "@color/colorPrimary"
            android:layout_width= "match_parent"
            android:layout_height= "60dp"/>

    </LinearLayout>

</RelativeLayout>

Step 6: MainActivity.java file

First we have to import the library inside the ActivityMain.java

//library 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.ads.nativetemplates.NativeTemplateStyle;
import com.google.android.ads.nativetemplates.TemplateView;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

Now inside the MainActivity class we create object of AdLoader, TemplateView, Button (loadAdBtn, showAdBtn, hideAdBtn) and a boolean variable to store the status of ad loaded or not as shown below:

//creating Object of AdLoader
private AdLoader adLoader ;

// simple boolean to check the status of ad
private boolean adLoaded=false;

//creating Object of Buttons
private Button loadAdBtn;
private Button showAdBtn;
private Button hideAdBtn;

//creating Template View object
TemplateView template;

Now inside the onCreate we initialize the MobileAds and showing 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 initilize the Button and AdLoader inside the onCreate method after initializing the SDK. AdLoader constructor has 2 parameter:

  • 1st Parameter : Context

  • 2nd Paramnter: AdId (we are using test id provided by admob for this tutorial, you can change it with your own app native ad id)

and add the UnifiedNativeAdLoadedListener and inside onUnifiedNativeAdLoaded method we initialize as shown below:

// Initializing the Button  objects to their respective views from activity_main.xml file
loadAdBtn = (Button) findViewById(R.id.loadNativeBtn);
showAdBtn = (Button) findViewById(R.id.showNativeBtn);
hideAdBtn = (Button) findViewById(R.id.hideNativeBtn);

//Initializing the AdLoader   objects
adLoader = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110").forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {

	private ColorDrawable background;@Override
	public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {

		NativeTemplateStyle styles = new
		NativeTemplateStyle.Builder().withMainBackgroundColor(background).build();

		template = findViewById(R.id.nativeTemplateView);
		template.setStyles(styles);
		template.setNativeAd(unifiedNativeAd);
		adLoaded = true;
		// Showing a simple Toast message to user when Native an ad is Loaded and ready to show
		Toast.makeText(MainActivity.this, "Native Ad is loaded, now you can show the native ad", Toast.LENGTH_LONG).show();

	}

}).build();

Now we will create a simple method loadNativeAd() to load the Native Ad inside MainActivity class as show below:

private void loadNativeAd()
{
    // Creating  an Ad Request
    AdRequest adRequest = new AdRequest.Builder().build() ;

    // load Native Ad with the Request
    adLoader.loadAd(adRequest) ;

    // Showing a simple Toast message to user when Native an ad is Loading
    Toast.makeText (MainActivity.this, "Native Ad is loading ", Toast.LENGTH_LONG).show() ;

}

Next, we create another method showNativeAd() to show the Native Ad to the user if it is loaded and if it is not loaded we will load the Native ad using the above method loadNativeAd() and show the toast message to the user according to the condition as shown below:

private void showNativeAd()
{
    if ( adLoaded )
    {
        template.setVisibility( View.VISIBLE) ;
        // Showing a simple Toast message to user when an Native ad is shown to the user
        Toast.makeText (MainActivity.this,  "Native Ad  is loaded and Now showing ad  ", Toast.LENGTH_LONG).show() ;
    }
    else
    {
        //Load the Native ad if it is not loaded
        loadNativeAd() ;

        // Showing a simple Toast message to user when Native ad is not loaded
        Toast.makeText (MainActivity.this,  "Native Ad is not Loaded ", Toast.LENGTH_LONG).show() ;
    }
}

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 our activity_main.xml file:

//OnClickListener listeners for loadAdBtn and showAdBtn buttons
loadAdBtn.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( View view) {
        //calling the loadNativeAd method to load  the Native Ad
        loadNativeAd() ;
    }
});

showAdBtn.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( View view) {
        //calling the showNativeAd method to show the Native Ad
        showNativeAd() ;
    }
});

hideAdBtn.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( View view) {
        //calling the showNativeAd method to hide the Native Ad
        hideNativeAd() ;
    }
});

The Ccompleted code of MainActivity.java is shown below:

package com.studytonight.project;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

//library 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.ads.nativetemplates.NativeTemplateStyle;
import com.google.android.ads.nativetemplates.TemplateView;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

public class MainActivity extends AppCompatActivity {

	//creating Object of AdLoader
	private AdLoader adLoader;

	// simple boolean to check the status of ad
	private boolean adLoaded = false;

	//creating Object of Buttons
	private Button loadAdBtn;
	private Button showAdBtn;
	private Button hideAdBtn;

	//creating Template View object
	TemplateView template;

	@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 Button  objects to their respective views from activity_main.xml file
		loadAdBtn = (Button) findViewById(R.id.loadNativeBtn);
		showAdBtn = (Button) findViewById(R.id.showNativeBtn);
		hideAdBtn = (Button) findViewById(R.id.hideNativeBtn);

		//Initializing the AdLoader   objects
		adLoader = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110").forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {

			private ColorDrawable background;@Override
			public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {

				NativeTemplateStyle styles = new
				NativeTemplateStyle.Builder().withMainBackgroundColor(background).build();

				template = findViewById(R.id.nativeTemplateView);
				template.setStyles(styles);
				template.setNativeAd(unifiedNativeAd);
				adLoaded = true;
				// Showing a simple Toast message to user when Native an ad is Loaded and ready to show
				Toast.makeText(MainActivity.this, "Native Ad is loaded ,now you can show the native ad  ", Toast.LENGTH_LONG).show();
			}

		}).build();

		//OnClickListener listeners for loadAdBtn and showAdBtn buttons
		loadAdBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {
				//calling the loadNativeAd method to load  the Native Ad
				loadNativeAd();
			}
		});

		showAdBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {
				//calling the showNativeAd method to show the Native Ad
				showNativeAd();
			}
		});

		hideAdBtn.setOnClickListener(new View.OnClickListener() {@Override
			public void onClick(View view) {
				//calling the showNativeAd method to hide the Native Ad
				hideNativeAd();
			}
		});
	}

	private void loadNativeAd() {
		// Creating  an Ad Request
		AdRequest adRequest = new AdRequest.Builder().build();

		// load Native Ad with the Request
		adLoader.loadAd(adRequest);

		// Showing a simple Toast message to user when Native an ad is Loading
		Toast.makeText(MainActivity.this, "Native Ad is loading ", Toast.LENGTH_LONG).show();
	}

	private void showNativeAd() {
		if (adLoaded) {
			template.setVisibility(View.VISIBLE);
			// Showing a simple Toast message to user when an Native ad is shown to the user
			Toast.makeText(MainActivity.this, "Native Ad  is loaded and Now showing ad  ", Toast.LENGTH_LONG).show();

		}
		else {
			//Load the Native ad if it is not loaded
			loadNativeAd();

			// Showing a simple Toast message to user when Native ad is not loaded
			Toast.makeText(MainActivity.this, "Native Ad is not Loaded ", Toast.LENGTH_LONG).show();

		}
	}

	private void hideNativeAd() {

		if (adLoaded) {
			// hiding the Native Ad when it is loaded
			template.setVisibility(View.GONE);

			// Showing a simple Toast message to user when Native ad
			Toast.makeText(MainActivity.this, "Native Ad is hidden ", Toast.LENGTH_LONG).show();

		}
	}
}

Output:

In the below snapshots, you can see how the Native Ad will look in the android application.

Small Native ad show at the bottom of the user device screen

admob native ad example

Small Native ad show at the top of the user device screen,

admob native ad example

Medium Native ad show at the bottom of the user device screen:

Admob native ad example

Medium Native ad show at the top of the user device screen,

Admob native Ads example

Conclusion:

In just 6 simple steps we have integrated and shown you the basic example for creating a Google Admob Native Ad. If you face any issue while doing this, please share it in the comment section below and we will be happy to help.


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.