Admob is the #1 mobile advertising platform to grow your app business and is powered by Google’s ad technology. You can integrate AdMob in your android application and start earning right away. The best way to use AdMob is with Firebase, though Google Mobile Ads SDK remains available as a standalone SDK which can also be used to integrate Admob with your android application. Admob publishers can start taking advantage of Firebase’s free and unlimited analytics solution to monetize more intelligently, just by linking with Firebase and importing the Firebase SDK into your android application. In this tutorial we will be showing how to integrate Admob with your android application using Firebase.
Now let us create an android application on which we can integrate Firebase Admob to display Banner ads, Interstitial ads and Native Ads.
2. When you are prompted to add an activity to your application choose Blank Activity and click on next button.
3. In the next step click on Finish and in few seconds your application should be loaded in Android Studio.
4. Open build.gradle(Module:App) file of your application and add the following dependencies inside dependencies section of build.gradle (Module:App) file.
5. The application requires following permissions to work. Your app might not work unless you add these permissions to your AndroidManifest.xml file.
list_item_native_ad.xml
activity_movie_info.xml.
color.xml
style.xml
string.xml
Movie.java
Note : If you are testing on an Emulator then you can use the follwing line which is commented in the code.
MovieAdapter.java
MovieInfoActivity.java
Now let us create an android application on which we can integrate Firebase Admob to display Banner ads, Interstitial ads and Native Ads.
Create a new Android
1. Create a new Android Project in Android Studio. Give it a name and select the Minimum SDK on which your app will run on. I chose API 16 : Android 4.1 (JELLY_BEAN).2. When you are prompted to add an activity to your application choose Blank Activity and click on next button.
3. In the next step click on Finish and in few seconds your application should be loaded in Android Studio.
4. Open build.gradle(Module:App) file of your application and add the following dependencies inside dependencies section of build.gradle (Module:App) file.
5. The application requires following permissions to work. Your app might not work unless you add these permissions to your AndroidManifest.xml file.
Get Firebase Configuration File
Confiration Firebase With Admob
Open your activity_main.xml file and add the following code. We have a RecyclerView to hold list of movies and an AdView. AdView is a class that represents the advertising banners in the Admob SDK. This is where the banner ad from Admob gets loaded once we run our application.list_item_native_ad.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="132dp">
<com.google.android.gms.ads.NativeExpressAdView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/nativeAd"
ads:adSize="FULL_WIDTHx132"
ads:adUnitId="@string/native_ad_unit_id"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
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"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/list_movies"
android:paddingTop="50dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/banner_ad"
android:background="@android:color/white"
app:layoutManager="LinearLayoutManager"
tools:listitem="@layout/item_movie" />
<com.google.android.gms.ads.AdView
android:id="@+id/banner_ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id" />
</android.support.design.widget.CoordinatorLayout>
Create a new XML layout resource file under res->layout folder and name it as activity_movie_info.xml. It includes a CardView and a Textview inside it.activity_movie_info.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MovieInfoActivity">
<android.support.v7.widget.CardView
app:contentPadding="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/cardview_light_background"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_movie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Title"
android:textColor="@android:color/black"
android:textSize="26sp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
At this point of time, your build.gradle (Module:app) file might look like below.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And also,at this point the build.gradle (Module:project) file should look like below.
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "in.wolaris.firebase.admob"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
compile 'com.google.firebase:firebase-ads:10.2.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
Create colors.xml file in the values folder and add the following code. You can change the colors to change the look of the application.color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
The styles.xml file in the values folder looks like this.style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
The strings.xml file in the values folder looks like this. Always keep a habit of including all your string resources in this file. Replace the values of following resources with the Ad unit Ids you have created in the previous part of this tutorial.string.xml
<resources>
<string name="app_name">Firebase With Admob</string>
<string name="banner_ad_unit_id">YOUR_BANNER_AD_UNIT_ID_HERE</string>
<string name="interstitial_ad_unit_id">YOUR_INTERSTITIAL_AD_UNIT_ID_HERE</string>
<string name="native_ad_unit_id">YOUR_NATIVE_AD_UNIT_ID_HERE</string>
</resources>
Download drawble folder movies banner
Create a new Java class under your package and name it as Movie.java. This is our domain class which represents a Movie. Each movie will have a name, number of likes and a poster associated with it.Movie.java
package in.wolaris.firebase.admob;
import android.support.annotation.DrawableRes;
public class Movie {
private String mName;
private int likes;
@DrawableRes
private int mImage;
public Movie(String name, int likes,
@DrawableRes int mImage) {
this.mName = name;
this.likes = likes;
this.mImage = mImage;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public int getmImage() {
return mImage;
}
public void setmImage(int mImage) {
this.mImage = mImage;
}
}
Open your MainActivity.java and add the following code in it. We are displaying the list of movies in a RecyclerView with the help of an adapter class. We have loaded Banner Ads, Interstitial Ads in the MainActivity itself.
package in.wolaris.firebase.admob;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
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;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String TEST_DEVICE_ID = "YOUR_DEVICE_ID";
private AdView mBannerAd;
private InterstitialAd mInterstitialAd;
private RecyclerView mRecyclerView;
private Toolbar mToolbar;
private String clickedMovieName;
public static List<Movie> listOfMovies = new ArrayList<>();
static {
listOfMovies.add(new Movie("Avatar 2",
4252, R.drawable.avatar2));
listOfMovies.add(new Movie("Power Rangers",
9993, R.drawable.powerrangers));
listOfMovies.add(new Movie("Beauty and the Beast",
9654, R.drawable.beautyandthebeast));
listOfMovies.add(new Movie("World War Z 2",
1244, R.drawable.worldwarz2));
listOfMovies.add(new Movie("Fate of the Furious",
6324, R.drawable.fastandfurious));
listOfMovies.add(new Movie("Fifty Shades Darker",
4574, R.drawable.fiftyshadesdarker));
listOfMovies.add(new Movie("Pirates of the Carribean",
2542, R.drawable.pirates));
listOfMovies.add(new Movie("Smurfs",
6412, R.drawable.smurfs));
listOfMovies.add(new Movie("Logan",
3647, R.drawable.logan));
listOfMovies.add(new Movie("Transformers",
9475, R.drawable.transformers));
listOfMovies.add(new Movie("Thor",
9475, R.drawable.thorragnorak));
listOfMovies.add(new Movie("Maze Runner Death Cure",
9475, R.drawable.mazerunnerdeathcure));
listOfMovies.add(new Movie("Spider Man Home Coming",
9475, R.drawable.spidermanhomecoming));
for (int i = 0; i < listOfMovies.size(); i++) {
if (i > 0 && i % 3 == 0) {
//This is dummy movie that will be added in every 3rd position of the list
//As Native ads will be displayed in every 3rd position we cant have our Movies in 3rd pos
listOfMovies.add(i, new Movie("Thor",
9475, R.drawable.thorragnorak));
//Or you can add a null value instead of dummy movie
//listOfMovies.add(i,null);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.list_movies);
mBannerAd = (AdView) findViewById(R.id.banner_ad);
mInterstitialAd = new InterstitialAd(this);
setSupportActionBar(mToolbar);
//Populating the list of Movies
MovieAdapter moviesAdapter = new MovieAdapter(
this,
listOfMovies,
new MovieAdapter.MovieItemClick() {
@Override
public void onMovieClick(Movie clickedMovie) {
clickedMovieName = clickedMovie.getmName();
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Intent intent = new Intent(getApplicationContext(), MovieInfoActivity.class);
//Sending the name of the clicked movie to next activity
intent.putExtra("clickedMovieName", clickedMovieName);
startActivity(intent);
}
}
});
mRecyclerView.setAdapter(moviesAdapter);
//Banner Ad Request
//Add the following code if you are testing on a real device
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(TEST_DEVICE_ID)
.build();
//You can add the following code if you are testing in an emulator
/*AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();*/
mBannerAd.loadAd(adRequest);
mBannerAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
Toast.makeText(getApplicationContext(), "Closing the Banner Ad", Toast.LENGTH_LONG).show();
}
@Override
public void onAdLoaded() {
Toast.makeText(getApplicationContext(), "Banner Ad is loaded", Toast.LENGTH_LONG).show();
}
});
//Interstitial Ad Request
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
requestNewInterstitial();
Intent intent = new Intent(getApplicationContext(), MovieInfoActivity.class);
intent.putExtra("clickedMovieName", clickedMovieName);
startActivity(intent);
}
});
requestNewInterstitial();
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(TEST_DEVICE_ID)
.build();
//You can add the following code if you are testing in an emulator
/*AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();*/
mInterstitialAd.loadAd(adRequest);
}
@Override
protected void onResume() {
super.onResume();
if (mBannerAd != null) {
mBannerAd.resume();
}
}
@Override
protected void onPause() {
super.onPause();
if (mBannerAd != null) {
mBannerAd.pause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBannerAd != null) {
mBannerAd.destroy();
}
}
}
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
We need an adapter class to render the data in our RecyclerView. So create a new Java class under your package and name it as MoviesAdapter.java. As we are displaying native ads for every 3rd item in our RecyclerView, we need to distinguish between Native ads item and Movie item. Hence we are using 2 different ViewHolders.MovieAdapter.java
package in.wolaris.firebase.admob;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.NativeExpressAdView;
import java.util.ArrayList;
import java.util.List;
public class MovieAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private List<Movie> mItems = new ArrayList<>();
private MovieItemClick mItemClickListener;
private static final int DEFAULT_VIEW_TYPE = 1;
private static final int NATIVE_AD_VIEW_TYPE = 2;
public MovieAdapter(Context context,
List<Movie> movies,
MovieItemClick movieItemClick) {
mContext = context;
mItems = movies;
mItemClickListener = movieItemClick;
}
@Override
public int getItemViewType(int position) {
if (position>1 && position % 3 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.item_movie, parent, false);
return new MyViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
return new NativeAdViewHolder(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof MyViewHolder)) {
return;
}
Movie currentItem = mItems.get(position);
MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.name.setText(currentItem.getmName());
myViewHolder.likes.setText(""+currentItem.getLikes());
myViewHolder.likeImage.setImageResource(R.drawable.ic_favorite_black_24dp);
myViewHolder.likeImage.setVisibility(View.VISIBLE);
Glide.with(mContext)
.load(currentItem.getmImage())
.centerCrop()
.into(myViewHolder.movieImage);
}
@Override
public int getItemCount() {
return mItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public TextView name;
public TextView likes;
public ImageView likeImage;
public ImageView movieImage;
public MyViewHolder(View itemView) {
super(itemView);
likeImage=(ImageView)itemView.findViewById(R.id.iv_like_image);
name = (TextView) itemView.findViewById(R.id.tv_name);
likes = (TextView) itemView.findViewById(R.id.tv_likes);
movieImage = (ImageView) itemView.findViewById(R.id.iv_movie_image);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition();
mItemClickListener.onMovieClick(mItems.get(position));
}
}
public class NativeAdViewHolder extends RecyclerView.ViewHolder {
private final NativeExpressAdView mNativeAd;
public NativeAdViewHolder(View itemView) {
super(itemView);
mNativeAd = (NativeExpressAdView) itemView.findViewById(R.id.nativeAd);
mNativeAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
super.onAdLoaded();
if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLoaded");
}
}
@Override
public void onAdClosed() {
super.onAdClosed();
if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdClosed");
}
}
@Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdFailedToLoad");
}
}
@Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLeftApplication");
}
}
@Override
public void onAdOpened() {
super.onAdOpened();
if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdOpened");
}
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(MainActivity.TEST_DEVICE_ID)
.build();
//You can add the following code if you are testing in an emulator
/*AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();*/
mNativeAd.loadAd(adRequest);
}
}
interface MovieItemClick {
void onMovieClick(Movie clickedMovie);
}
}
Create a new Java class under your package and name it as MovieInfoActivity.java. This is an Activity which gets opened when the user clicks on a movie item in the RecyclerView. It gets the name of the movie on which the user has clicked from the intent passed to it and displays it in a CardView.MovieInfoActivity.java
package in.wolaris.firebase.admob;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MovieInfoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_info);
String clickedMovieName = getIntent().getStringExtra("clickedMovieName");
TextView tv = (TextView) findViewById(R.id.tv_movie);
tv.setText(clickedMovieName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Add the name of the activity you created in the previous step to your AndroidManifest.xml file as shown below. This is how your AndroidManifest.xml should look at the end of this project.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wolaris.firebase.admob">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>