Integrating AdMob into your Android applications can be a great way to generate revenue. While Jetpack Compose is the future, many existing projects still utilize XML-based UI layouts. This post provides a comprehensive guide on how to integrate AdMob ads with your XML-based Android UI, covering all the necessary steps from setting up AdMob to implementing various ad formats.
Why Integrate AdMob with XML-Based UI?
Even though Jetpack Compose is gaining popularity, a significant number of Android apps still use XML for their UI layouts. Therefore, knowing how to integrate AdMob ads into these XML-based UIs is essential for monetizing existing applications.
Prerequisites
Before you start, make sure you have:
- An AdMob account. If not, sign up at AdMob.
- An existing Android project with an XML-based UI.
- The latest version of Android Studio.
Step 1: Set Up AdMob in the Google AdMob Console
First, you need to create an AdMob app and get the App ID and Ad Unit IDs.
- Go to the AdMob website and sign in.
- Click on Apps in the sidebar.
- Click on Add app.
- Choose the platform (Android).
- Select whether your app is listed on the Google Play Store. If yes, search for your app and link it. If not, choose No and continue.
- Enter your app name and click Add app.
Step 2: Get the App ID and Ad Unit IDs
- After creating the app, you’ll be taken to the app dashboard.
- In the sidebar, click on App settings.
- You’ll find your App ID listed. Copy this; you’ll need it later.
- To create an Ad Unit, go back to your app’s overview page and click Add ad unit.
- Choose an ad format (Banner, Interstitial, Rewarded, etc.).
- Enter an Ad Unit name and configure any settings (like eCPM floor).
- Click Create ad unit.
- You’ll receive the Ad Unit ID. Copy this; you’ll need it to display the ad in your app.
- Repeat this process for any other ad formats you wish to use.
Step 3: Add AdMob to Your Android Project
Add the Google Mobile Ads SDK to your project.
- Open your Android project in Android Studio.
- Open the
build.gradle (Project: YourProjectName)
file and add the Google Maven repository:
allprojects {
repositories {
google()
mavenCentral()
}
}
- Open the
build.gradle (Module: app)
file and add the dependency for the Google Mobile Ads SDK:
dependencies {
implementation 'com.google.android.gms:play-services-ads:23.0.0' // Make sure to check for the latest version
}
- Click on Sync Now to sync your project with the Gradle files.
Step 4: Initialize the Mobile Ads SDK
Initialize the Mobile Ads SDK in your Application
class or your main Activity
’s onCreate
method.
- If you don’t have an
Application
class, create one:
import android.app.Application;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
}
}
- Make sure to declare your
Application
class in yourAndroidManifest.xml
file:
...
Step 5: Implement Ad Formats
Now, let’s look at how to implement different ad formats.
Banner Ads
Banner ads are rectangular ads that appear at the top, bottom, or in other parts of the screen.
- Add the
AdView
to your XML layout file:
- In your
Activity
orFragment
, load the ad:
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, initializationStatus -> {});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
}
Interstitial Ads
Interstitial ads are full-screen ads that cover the interface of an app.
- Declare an
InterstitialAd
variable:
private InterstitialAd mInterstitialAd;
- Load the Interstitial ad:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, initializationStatus -> {});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("YOUR_INTERSTITIAL_AD_UNIT_ID");
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
@Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
@Override
public void onAdOpened() {
// Code to be executed when the ad is displayed.
}
@Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
@Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
@Override
public void onAdClosed() {
// Code to be executed when the interstitial ad is closed.
loadAd(); // Preload the next ad
}
});
}
private void showInterstitialAd() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
loadAd();
}
}
private void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
// Call showInterstitialAd() when you want to display the ad
}
Rewarded Ads
Rewarded ads give users in-app rewards for watching short videos and interacting with playable ads and surveys.
- Declare a
RewardedAd
variable:
private RewardedAd rewardedAd;
- Load the Rewarded ad:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
public class MainActivity extends AppCompatActivity {
private RewardedAd rewardedAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, initializationStatus -> {});
loadRewardedAd();
}
private void loadRewardedAd() {
RewardedAd.load(this, "YOUR_REWARDED_AD_UNIT_ID",
new AdRequest.Builder().build(), new RewardedAdLoadCallback(){
@Override
public void onAdLoaded(RewardedAd ad) {
rewardedAd = ad;
Log.d("TAG", "RewardedAd was loaded.");
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d("TAG", "Ad was shown.");
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e("TAG", "Ad failed to show.");
rewardedAd = null;
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d("TAG", "Ad was dismissed.");
rewardedAd = null;
loadRewardedAd();
}
});
}
@Override
public void onAdFailedToLoad(LoadAdError error) {
// Handle the error.
Log.d("TAG", error.toString());
rewardedAd = null;
}
}
);
}
private void showRewardedAd() {
if (rewardedAd != null) {
rewardedAd.show(MainActivity.this, rewardItem -> {
// Handle the reward.
Log.d("TAG", "The user earned the reward.");
// ... Add code to reward the user ...
});
} else {
Log.d("TAG", "The rewarded ad wasn't loaded yet.");
}
}
// Call showRewardedAd() when you want to display the ad
}
Step 6: Test Your Ad Implementation
Always test your ad implementation thoroughly to ensure everything is working correctly. Use AdMob’s test ad units during development to avoid invalid impressions and potential policy violations.
Test Ad Unit IDs:
- Banner:
ca-app-pub-3940256099942544/6300978111
- Interstitial:
ca-app-pub-3940256099942544/1033173712
- Rewarded:
ca-app-pub-3940256099942544/5224354917
Conclusion
Integrating AdMob with your XML-based UI is crucial for monetizing your existing Android applications. This guide has provided you with step-by-step instructions on how to set up AdMob, add the Mobile Ads SDK to your project, and implement different ad formats like banner, interstitial, and rewarded ads. Remember to test your implementation thoroughly using test ad units before deploying your app to production. With these steps, you’ll be well-equipped to start generating revenue from your Android app using AdMob.