How to add AdMob to Android app

Khoa Pham
Khoa Pham
Nov 6 · 1 min read

Use AdMob with Firebase

build.gradle

buildscript {
repositories {
google()
jcenter()

}
dependencies {
classpath 'com.google.gms:google-services:4.3.2'
}
}

app/build.gradle

class Version {
class Firebase {
static def analytics = "17.2.0"
static def ads = "18.2.0"
}
}
dependencies {
implementation "com.google.firebase:firebase-analytics:$Version.Firebase.analytics"
implementation "com.google.firebase:firebase-ads:$Version.Firebase.ads"
}
apply plugin: 'com.google.gms.google-services'

Manifest.xml

<manifest>
<application>
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="[ADMOB_APP_ID]"/>
</application>
</manifest>

MyApplication.kt

class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
MobileAds.initialize(this)
}
}

AdView

fragment.xml

<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-123456/123456"
ads:layout_constraintBottom_toBottomOf="parent"
ads:layout_constraintLeft_toLeftOf="parent"
ads:layout_constraintRight_toRightOf="parent"/>

Fragment.kt

import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
val request = AdRequest.Builder().build()
adView.loadAd(request)

Troubleshooting

Link your app to Firebase option not showing

app/build.gradle

dependencies {
implementation 'com.google.android.gms:play-services-ads:18.2.0'
}

Cannot fit requested classes in a single dex file

app/build.gradle

android {
defaultConfig {
multiDexEnabled true
}
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}

Read more

Fantageek

Simple apps that make sense

Khoa Pham

Written by

Khoa Pham

My apps https://onmyway133.github.io/

Fantageek

Fantageek

Simple apps that make sense

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade