How to add AdMob to Android app

Issue #431

Use AdMob with Firebase

build.gradle

1
2
3
4
5
6
7
8
9
10
buildscript {
repositories {
google()
jcenter()

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

app/build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
<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

1
2
3
4
5
6
7
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()

MobileAds.initialize(this)
}
}

AdView

fragment.xml

1
2
3
4
5
6
7
8
9
10
<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

1
2
3
4
5
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView

val request = AdRequest.Builder().build()
adView.loadAd(request)

Troubleshooting

app/build.gradle

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

Cannot fit requested classes in a single dex file

app/build.gradle

1
2
3
4
5
6
7
8
9
10

android {
defaultConfig {
multiDexEnabled true
}
}

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

Read more

Comments