In this tutorial, you'll learn about how to integrate AdMob so you can make money from that awesome Android app you wrote—come on, who doesn't want that? AdMob is among the biggest mobile advertising platforms in the market, and it is owned by Google.
There are a few different ways to monetize your apps in Android: paid downloads, paid subscriptions, in-app purchases, and by displaying ads. You can combine them, but is recommended you pick a single model. In this tutorial, you'll learn about how to monetize your app by displaying ads.
The kinds of ads you'll create in this tutorial are banner, interstitial, and native express ads. I'll explain each of them and show you how to implement them in your application. But before that, let's first of all see how to integrate the Mobile Ads SDK and initialize it.
Create an Android Studio Project
In Android Studio, create a new project named MainActivity
.
Include the Mobile Ads SDK
To begin integration of AdMob with your app, you'll need to first include the Mobile Ads SDK to your app module build.gradle
file:
compile 'com.google.android.gms:play-services-ads:11.0.2'
If you are going to integrate Firebase into your app, then you should use the SDK which is part of Firebase:
compile 'com.google.firebase:firebase-ads:11.0.2'
Check out the some of our Firebase tutorials here on Envato Tuts+ if you need help getting started with Firebase:
Make sure you sync the project after adding it the SDKs so as to pull the libraries from the internet into your application.
Initialize MobileAds
You need to initialize the Mobile Ads SDK before you can load ads on your Android app, so do this as early as possible. We create a class which extends the Application
class, and then we initialize the MobileAds
SDK in the onCreate()
method of that class, because this method is called only once when the app is launched.
import com.google.android.gms.ads.MobileAds; import android.app.Application; public class App extends Application { @Override public void onCreate() { super.onCreate(); MobileAds.initialize(this, "ca-app-pub-3940256099942544/6300978111"); } }
The second argument supplied to the static method initialize()
of the MobileAds
class should be your AdMob application ID you got when you signed up for AdMob. In this case, we are using the public application ID provided by Google for demo purposes.
Modify the Manifest File
We need to add the application class we created to the application tag name attribute in our AndroidManifest.xml file.
<application android:name=".App"></application>
While in this file, also make sure to include the INTERNET
permission so that Google mobile ads can run.
<!-- 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"/>
In the code snippet below, we added the AdActivity
to our AndroidManifest.xml file within the application tag.
<activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
This activity is provided by the SDK. It is useful in banner ads to fire up the ad to be viewed when the user clicks on the ad, while for an interstitial ad, it is used for displaying the ad when the user clicks on it.
1. Banner Ads
Banner ads cover a part of the currently visible screen. In other words, any content in your app and the ad are displayed together on the screen. This improves the user experience because your users can keep on using your app while the ad is showing, unlike an interstitial ad (just hang on, we'll get to that shortly). Note that a banner ad can be text or an image.
Let's look at how to implement a banner ad.
Include a Banner Ad in Your Layout
AdView
is a custom ViewGroup
that will contain the banner ad, so we need to edit our activity_banner_ad.xml layout file to include this view.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="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="com.chikeandroid.tutsplus_admob.MainActivity"><TextView android:text="Hello World" android:layout_width="wrap_content" android:layout_height="wrap_content" /><com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" ads:adSize="BANNER" ads:adUnitId="ca-app-pub-3940256099942544/6300978111"></com.google.android.gms.ads.AdView></RelativeLayout>
We are defining the AdView
size by using the attribute ads:adSize
and setting it to BANNER
. Other alternatives available are LARGE_BANNER
, FULL_BANNER
, SMART_BANNER
, etc.
The ads:adUnitId
AdView
attribute is set to a sample ad unit provided by Google. You'll have to update this with an ad unit associated with your account if you want to actually make money from your ads!
The ad unit ID identifies an ad placement, and you can find it in the AdMob admin console. This ID will tell AdMob the kind of ad to be displayed on your app and also the display format (image, text, or video).
Load the Ad
For us to finally show the ad, we need to make a request and then show it in the AdView
we created above in the BannerAdActivity
class.
import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class BannerAdActivity extends AppCompatActivity { private AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mAdView.loadAd(adRequest); } }
We made an ad request by creating an instance of AdRequest using the builder. Then we used the method addTestDevice()
, passing in a device id as an argument to receive test ads to the device, which in our case is the emulator. We then finally called the AdView
method loadAd()
that takes in this AdRequest
instance and then loads the ad on a background thread (so as not to block the UI/main thread).
Test the Ad
At this point, we can run our project and see the result.
From the screenshot above, we can see that our test banner ad is showing below the view. Now interact with the ad by clicking on it.
Listening for Ad Events With AdListener
Let's now explore the events or callbacks we can observe in an ad. These are the events available:
onAdLoaded()
: this method is fired when the ad is retrieved.onAdOpened()
: this method is invoked when the ad is opened.onAdClosed()
: this method is fired when the ad is closed.onAdLeftApplication()
: this method is invoked when the user has left the application.onAdFailedToLoad(int errorCode)
: this is fired when a request for the ad fails. The code can be one ofERROR_CODE_NETWORK_ERROR
,ERROR_CODE_INVALID_REQUEST
,ERROR_CODE_NO_FILL
, orERROR_CODE_INTERNAL_ERROR
.
// ... @Override protected void onCreate(Bundle savedInstanceState) { // ... mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); Toast.makeText(MainActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); Toast.makeText(MainActivity.this, "onAdOpened()", Toast.LENGTH_SHORT).show(); } @Override public void onAdClosed() { super.onAdClosed(); Toast.makeText(MainActivity.this, "onAdClosed()", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); Toast.makeText(MainActivity.this, "onAdFailedToLoad()", Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); Toast.makeText(MainActivity.this, "onAdLeftApplication()", Toast.LENGTH_SHORT).show(); } }); } @Override public void onPause() { // This method should be called in the parent Activity's onPause() method. if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); // This method should be called in the parent Activity's onResume() method. if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { // This method should be called in the parent Activity's onDestroy() method. if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } }
After adding the listener, run the project again and interact with the ad. Observe the events being invoked by watching the toasts we created.
2. Interstitial Ads
We have seen how easy it is to display a banner ad. Now let's look at how to create interstitial ads.
Interstitial ads are ads that cover the whole screen of your application, giving no room for other views of your app to show (as we'll see shortly). Since this takes over the entire screen and also takes some time to load if the network is slow, you need to be careful not to irritate your users. So ideally these interstitial ads should be shown during natural breaks in your app, e.g. between levels in a game, and not when users are in the middle of some other task.
import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class InterstitialAdActivity extends AppCompatActivity { private InterstitialAd mInterstitialAd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadInterstitialAd(); } private void loadInterstitialAd() { mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); Toast.makeText(MainActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show(); if(mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); Toast.makeText(MainActivity.this, "onAdFailedToLoad()", Toast.LENGTH_SHORT).show(); } }); AdRequest adRequest = new AdRequest.Builder().build(); mInterstitialAd.loadAd(adRequest); } }
In the code above, we declared and initialized an instance of the class InterstitialAd
in the InterstitialAdActivity
class. We set the add unit id by passing the Google-provided one as the only argument into the method setAdUnitId()
.
Just like what we did for the banner ad, we want to listen for events on the ad, so we set a listener to fire the overloaded methods onAdLoaded()
and onAdFailedToLoad(int i)
. We make an ad request by creating an instance of the AdRequest
class using its builder and then call the method loadAd()
, passing this request as an argument to the method. We use the method isLoaded()
to determine when the ad has been loaded and then call the method show()
to finally display it.
You can also add an AdListener
just like we did for the banner ad.
Test the Ad
At this point now, we can run the app and see the result.
In the screenshot above, you can see that our test interstitial ad is now showing.
3. Native Ads Express
Native Ads Express gives you (the publisher) the ability to customize the look and feel of ads so that they can fit naturally with your app. This customization is done by defining CSS templates in which you define your own fonts, colours, sizes, etc. from your AdMob account. You can't change the images, descriptions, and titles, though—these are set by the advertisers.
The customized ads can be displayed in your app in a NativeExpressAdView
.
Include NativeExpressAdView
in Your Layout
Below, we include the NativeExpressAdView
, which is a ViewGroup
, in our layout file. We also define the android:layout_height
and android:layout_width
to be wrap_content
. The ads:adSize
will be "320x300"
, and we'll use the Google-provided NativeExpress ad unit id (for demo purposes only).
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="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="com.chikeandroid.tutsplus_admob.BannerAdActivity"><TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Native Express Ad!" /><com.google.android.gms.ads.NativeExpressAdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" ads:adSize="320x300" ads:adUnitId="ca-app-pub-3940256099942544/2177258514"></com.google.android.gms.ads.NativeExpressAdView></RelativeLayout>
Load the Ad
Next, we build our AdRequest
and then begin loading the ad to be displayed. We'll also add code to respond to the Activity lifecycle callbacks. You can also add an AdListener
if you want, just like we did for the banner ad.
import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.NativeExpressAdView; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class NativeExpressAdActivity extends AppCompatActivity { NativeExpressAdView mNativeExpressAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_native_ad); mNativeExpressAdView = (NativeExpressAdView) findViewById(R.id.adView); AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); mNativeExpressAdView.loadAd(adRequestBuilder.build()); } @Override public void onResume() { super.onResume(); mNativeExpressAdView.resume(); } @Override public void onPause() { mNativeExpressAdView.pause(); super.onPause(); } @Override public void onDestroy() { mNativeExpressAdView.destroy(); super.onDestroy(); } }
Test the Ad
That's it! Now you can run the app and see your Native Express ad in action.
Create Your Own AdMob Account
Now that we have learned about the different types of ads, you can go ahead and integrate them into your application. To begin showing real ads and making money, you'll need an AdMob account—with real ad unit ids that are linked to real ads from advertisers. Just visit the AdMob website to sign up!
Conclusion
In this tutorial, you learned about AdMob and how to integrate different AdMob ad formats such as banner, interstitial, and native express ads on Android.
To learn more about AdMob on Android, do refer to the official documentation. And in the meantime, check out some of our other courses and tutorials on Android app development!
- Android SDKCreate an Intelligent App With Google Cloud Speech and Natural Language APIs
- Android SDKAndroid O: Phone Number Verification With SMS Tokens
- Android ThingsAndroid Things: Creating a Cloud-Connected Doorman