DEV Community

Cover image for Implementing Admob Ads With Jetpack Compose
Ethan
Ethan

Posted on • Originally published at ethan-dev.com

Implementing Admob Ads With Jetpack Compose

Introduction

Hello! ๐Ÿ˜Ž

In this tutorial I will show you how to implement Admob Advertising with Jetpack Compose.
I recently had to do this in my side project so I thought I'd share how I implemented it with you. ๐Ÿ˜ƒ


Requirements

You will need need a Google Admob account which you can create via the following link:

https://admob.google.com/home/

You will need to register an account via the above link before continuing this tutorial.


Creating A New Admob App/Unit

Once you have your account created, next you will need to create a new App via the Admob dashboard

Create Admob

Make sure to select Android, and then select if your app is already on the store, since this is a sample app I selected no.

Now that your app is created select it in the Admob Dashboard. And click on "Add Ad Unit"

Add Admob

Next you will be greeted with the following screen: I will using the Banner add unit for this tutorial.

Admob Select

Next give you Ad Unit a name, for this tutorial I used the name "sample" but feel free to change the name to your liking.

Configure Admob

After that you will be shown the app id and the app unit id, make sure to note these down as will we be using them in the application.

Now that we have created both our Admob app and app unit we can finally implement it into code and start using it. ๐Ÿ˜Š


Creating The Project

First we need to actually have a project to implement the above, fire up Android Studio and create a new Empty Compose project.

New Project

Next give the project a name and click on "Finish":

Android project name

Done! Now we can actually start coding!


Adding the Libraries And Variables

First we need to actually add the libraries and set a couple of variables.

To add the ad library open up your app's "build.gradle" and add the following implementation:

implementation 'com.google.android.gms:play-services-ads:21.3.0'
Enter fullscreen mode Exit fullscreen mode

Sync your project and next open up "AndroidManifest.xml" and add the following after activity ends:

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-5474571366428116~6242400131"
/>
Enter fullscreen mode Exit fullscreen mode

Make sure to change the value to the app id you were shown when creating the ad banner.

Next we need to include the ad unit id so open up "strings.xml" and add the following strings:

<resources>
    <string name="app_name">AdSample</string>

    <!-- for main title -->
    <string name="main_title">Admob Sample</string>

    <!-- for ad mob -->
    <string name="ad_mob_banner_id">ca-app-pub-5474571366428116/7958806488</string>
    <string name="ad_mob_test_banner_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>
Enter fullscreen mode Exit fullscreen mode

Note we also include the string for the test banner, this is a universal test banner that is used when in development mode. Make sure not to use the real banner id when you are editing your application. Also like the app id, make sure you are using your own ad unit id.

Now that we have defined the variables we can finally get coding the application. ๐Ÿ‘


Creating The Application

Now that we have everything defined we can now move on the coding part.

Create a new package called "components" and create a new file called "BannerAdView" and then fill it with the following:

package com.neko.adsample.components

import android.annotation.SuppressLint
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.neko.adsample.R

@SuppressLint("VisibleForTests")
@Composable
fun BannerAdView(
    isTest: Boolean = true
) {
    val unitId = if (isTest) stringResource(id = R.string.ad_mob_test_banner_id) else stringResource(
        id = R.string.ad_mob_banner_id
    )

    AndroidView(
        factory = { context ->
            AdView(context).apply {
                setAdSize(AdSize.BANNER)
                adUnitId = unitId
                loadAd(AdRequest.Builder().build())
            }
        }
    )
}
Enter fullscreen mode Exit fullscreen mode

I personally like to keep small components like this in their own components package. ๐Ÿ˜ธ

What this simple composable does is take a boolean which if true makes the adUnitId the test id or the real id if false. Make sure to set this variable to false when uploading the Google Store.

The composable sets up the adview using the Banner size and then loads an ad using the default AdRequest. Finally the ad view is returned. ๐Ÿ˜

Now that we have our AdBannerView we can actually use it in the "MainActivity", open it up and change it to the following:

package com.neko.adsample

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.neko.adsample.ui.theme.AdSampleTheme
import com.google.android.gms.ads.MobileAds
import com.neko.adsample.components.BannerAdView

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        MobileAds.initialize(this) {
        }

        super.onCreate(savedInstanceState)
        setContent {
            AdSampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = stringResource(id = R.string.main_title),
                            fontWeight = FontWeight.Bold
                        )

                        Spacer(modifier = Modifier.height(20.dp))

                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Center
                        ) {
                            BannerAdView()
                        }
                    }
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Done! Now fire up and emulator or an actual device and when the app loads you should see the following:

Admob app

If you don't see any ad, make sure that your app id is correct etc. ๐Ÿ‘€


Conclusion

Here I have shown how to implement simple banner ads into your application using Admob and Jetpack Compose.

Hopefully this has been helpful to you. (and future me ๐Ÿ˜‚)

Happy Coding ๐Ÿ˜Ž

As always you can get the code via:
https://github.com/ethand91/admob-sample


Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.

โ€œBuy Me A Coffeeโ€

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course

Top comments (0)