How to add MoPub Ads in your Android app using Kotlin

How to add MoPub Ads in your Android app using Kotlin

If you don’t have a MoPub account yet, check out the tutorial How to Create an Account on MoPub where I cover step by step how to make one, and get approved from Marketplace.

In this tutorial, I will show you how to add MoPub Ads in your Android app. We’ll cover all ad formats (Banner, Interstitial, Native, Native Video and Rewarded), we’re also going to implement Native ads inside a Recyclerview and Viewpager.

I highly recommend using MoPub Test Ad Units when you implement the following methods.

If you’re using ad units created from your MoPub account they might not work all the time at the beginning, because when you start the filling rate is low, so it’s better to start with the test ad units and when your app/update is production-ready, you switch to your own ad units.

Setting up MoPub

First, go to the build.gradle file of our project and paste:

Then, in the build.gradle (Module: app) add MoPub’s dependency:

If you want to use only a specific ad format, let’s say Native Ads, you can choose the dependency only for that format, to decrease the size of the SDK:

Now let’s jump into our AndroidManifest.xml file and add the following permissions for our ads (If you don’t want to use targeted ads, using user’s location, just comment out the line 6 and 7):

..also in the same file we add the MoPub Activities (choose the Activity for your ad format):

..and lastly, we have to add the following tag for the Google Play Services:

Now let’s go back to our build.gradle file of the app and add the dependency for the Google Play Services:

NOTE: If you use an ad format that includes video, MoPub recommends adding the following compileOptions in the build.gradle file of the app to prevent compilation errors with ExoPlayer 2.9.5 and later:

Android 9.0 (API 28) blocks all the connections without HTTPS protocol.

To make our ads work properly, we need to create a xml file (network_security_config.xml) under the xml folder of our project.

Right-click on the res folder of our project and choose New>Folder>XML Resources Folder and Finish.

Then right-click on the xml folder and choose New>XML resource file.

Give the name network_security_config and press OK.

Now paste the following code inside:

…next, we have to add this file in our AndroidManifest.xml inside the <application> tag:

For more details about that, look at Step 4. Add a Network Security Configuration File in MoPub Documentation.

Initializing MoPub

MoPub recommends that we need to initialize the SDK before requesting an ad in our app.

So I made a class (MyMoPub) where we initialize MoPub SDK(lines 9-13) and check if the country is covered by GDPR (lines 27-31).

Check out the tutorial How to create a Custom MoPub GDPR Consent Dialog in Android using Kotlin to create a custom dialog for the GDPR consent

If the user is living in a GDPR country, then we show the consent dialog to ask them for their permission to display personalized ads.

If you have multiple ad formats (e.g. Native and Banner ads) on the same screen, just give as a parameter one of the adunits.

Go to the MoPub Dashboard and create a new Banner ad unit (or Medium Rectangle) and press Save.

Creating a Banner Ad Unit
Creating a Medium Rectangle Ad Unit

Now that we have created the ad unit id, we are ready to add the Banner/Medium Rectangle (MoPubView) view at the bottom of the layout, like that:

… and in our Activity/Fragment class:

First, we initialize the SDK (line 12), next we create the Banner View and we request an ad (lines 21-23) and lastly, we create a listener that can inform us for every event (lines 27-49).

Interstitial Ads

Let’s go to the MoPub Dashboard and create a new Interstitial ad unit.

Give it a name, choose Full Screen and press Save.

Interstitial ads are very simple to integrate; you only need to add the following code to your Activity/Fragment:

As you see above, we initialize the SDK (line 10), create the Interstitial view, and prepare the ad to be ready to show on the user (lines 19-21). Last, we add a listener to check when it’s loaded.

In this example we call yourAppsShowInterstitialMethod() after we load the Interstitial ad, but in a real app, call this function when you want to show the ad to the user, for example, in a game when a round ends.

Native Ads

First, in the MoPub Dashboard, we create a new ad unit for our Native ads.

Then, we create the layout for our Native Ad.

Right-click on the layout folder and New>Layout resource file.

… and give it the name ‘mopub_native_ad_view’ and press OK.

Then, paste the following inside:

For different device sizes, we need a different height for the main ImageView of our Native Ad.

Let’s do that and create a file called dimen.xml by right-clicking on the values folder and choose New>Values resource file …

… and type the name dimens and press OK.

Now, lets do the same thing again for other screen sizes, but this time we will choose Smallest Screen Width from the list, press the >> button and give the value 400, 600 and 800.

And paste the following code in the dimens.xml:

.. the dimens.xml (sw400dp):

dimens.xml (sw600dp):

… and in the dimens.xml (sw800dp):

After we finished, our project looks like this:

Native Ads (Single View)

To integrate a Native Ad as a single view, we have to create a FrameLayout inside our Activity/Fragment.

This FrameLayout will contain the Native Ad layout we created earlier.

Next, in our Activity/Fragment Kotlin class we add:

In the line 15 we initialize the MoPub SDK, we create an event listener where we check if the Native ad got an impression or clicked, (lines 24-35), a network listener which we add the Native ad view in the FrameLayout of our Activity/Fragment (lines 37-49), and at the end we create the ViewBinder for our Native ad layout, and we send a request to get and ad from MoPub(lines 53-64)

And that’s it!

Native Ads (RecyclerView)

Let’s say that we have a RecyclerView already filled with data, and we want to put ads in it, an easy method is to use MoPub‘s adapter, MoPubRecyclerAdapter, which calculates the amount of cells with the ads automatically.

To do that, we use the MoPubRecyclerAdapter after the normal RecyclerView.Adapter of our RecyclerView:

Here, we initialize the MoPub SDK (line 11), then we add the native ads into our RecyclerView after we pass the normal adapter (lines 32-38).

When we add the native ads, we pass as a parameter the normal RecyclerView.Adapter to create the right amount of rows.

And done! Easy, huh?

Native Ads (ViewPager)

We already have an Activity/Fragment with a ViewPager in it, filled with data, and we want to have ads every 8 pages.

To do that, first, we need to edit our Activity/Fragment and create the Native Ads, then we add the adplacer (MoPubStreamAdPlacer), to insert the ads, into the ViewPager through the adapter (lines 60-66)

and the adapter of our ViewPager, in this example CustomPagerAdapter:

Next, we create the Fragment that contains the ad:

..and last we create the Fragment for our content:

Native Video Ads

NOTE: MoPub doesn’t seem to allow you anymore to create ad units for Native Video ads, in their platform, but you can implement the following integrations using the MoPub Test Ad Unit:02a2d288d2674ad09f3241d46a44356e

Native Video Ads use a different layout from the Native Ads. Instead of ImageView, they use a custom view called MediaLayout.

Right-click on the layout folder and New>Layout resource file.

… and give it the name ‘mopub_native_video_ad_view’ and press OK.

… and paste:

Native Video Ads (Single View)

The only difference from the Native Ad integration is that, here, we use a ViewBinder called MediaViewBinder to serve the video inside the ad.

First, we create a FrameLayout inside our Activity/Fragment:

This FrameLayout will contain the Native Video Ad layout we created before.

.. and in our Kotlin class we add the following.

Here, we initialize the MoPub SDK (line 14), next we create an event listener where we check if the Native Video ad got an impression or clicked, (lines 22-33), a network listener which we add the Native Video ad view in the FrameLayout of our Activity/Fragment (lines 36-48), and at the end we create the MediaViewBinder for our Native Video ad layout, and we send a request to get and ad from MoPub(lines 53-63)

Native Video Ads (RecyclerView)

To add Native Video Ads in a RecyclerView it’s very easy; We use exactly the same method as we did with Native Ads, we just add one more ViewBinder to support videos. MoPub also provide an adapter called MoPubRecyclerAdapter that calculates right amount of cells that we need with the ads in it.

To do that, we use the MoPubRecyclerAdapter after the normal RecyclerView.Adapter of our RecyclerView:

First, we initialize the MoPub SDK (line 10), then we add the native video ads into our RecyclerView after we pass the normal adapter (lines 31-35).

Rewarded Ads

Rewarded Ads works like the Interstital Ads, but you reward the user after having seen the video.

There’re two methods we can handle the reward, by client-side, having the app responsible to inform the user for the reward, and the server-side, where MoPub sends a callback to our server as the user completes seeing the video.

Client-side method is easier to implement because you don’t need to set up and run a callback server.

If you app is very complex, it’s recommended to use the server-side method, which is safer.

In this example, we’ll implement the client-side method. So, let’s dive into it!

First, let’s get the ad unit id from the MoPub Dashboard.

Now, let’s paste the following code in our Activity/Fragment:

We initialize the MoPub SDK, as we do every time before we display an ad on Activity/Fragment (line 23), then we create and set the listener MoPubRewardedVideoListener to listen to events, like when the rewarded ad dismissed, or when it’s completed and it’s time to reward the user (lines 11-43).

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Stay Connected

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!