How to integrate google ads in android app. Java and Kotlin Example
To integrate Google AdMob ads into your Android app, you’ll need to follow these general steps:
- Create a Google AdMob Account:
Go to the Google AdMob website (https://admob.google.com/) and sign up or log in with your Google account. Once logged in, create a new app or select an existing app to integrate Google ads. - Add Your App to Google AdMob:
After creating your app in the Google AdMob Dashboard, you need to add your Android app to the app settings. You’ll need to provide your app’s package name. - Set Up Google Mobile Ads SDK:
Add the Google Mobile Ads SDK to your Android project by including it in your app’sbuild.gradle
file. For Java:
implementation 'com.google.android.gms:play-services-ads:20.4.0'
For Kotlin:
implementation("com.google.android.gms:play-services-ads:20.4.0")
- Initialize Google Mobile Ads SDK:
In your app’sApplication
class orMainActivity
, initialize the Mobile Ads SDK with your AdMob app ID.
// Java
MobileAds.initialize(this);
// Kotlin
MobileAds.initialize(this)
- Add Google Ad Components:
Add Google ad components to your layout XML files where you want the ads to appear. You can use either Banner Ads, Interstitial Ads, or Native Ads, depending on your preference and app design. Example Banner Ad:
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="YOUR_AD_UNIT_ID"
/>
- Load Google Ads:
In your activity or fragment, load the ad into the ad view.
// Java
AdView adView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Kotlin
val adView = findViewById<AdView>(R.id.adView)
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
- Handle Ad Events:
You can also add listeners to handle events such as ad loading, clicks, and errors.
// Java
adView.setAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Handle ad loading error
}
@Override
public void onAdLoaded() {
// Ad loaded successfully
}
@Override
public void onAdClicked() {
// User clicked on the ad
}
});
// Kotlin
adView.adListener = object : AdListener() {
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
// Handle ad loading error
}
override fun onAdLoaded() {
// Ad loaded successfully
}
override fun onAdClicked() {
// User clicked on the ad
}
}
- Test Your Integration:
Before releasing your app, make sure to test your Google ads integration using test ads provided by Google. You can use test ad unit IDs to see test ads. - Publish Your App:
After testing, you can publish your app with Google ads integrated.
Remember to comply with Google’s advertising policies and guidelines when integrating and displaying ads in your app.