This document outlines the process of integrating Google Ad Manager Android SDK in your native app (Kotlin). Google Mobile SDK integration guide is available here.
|
IMPORTANT:
|
1. Configure the Gradle
Add the Google Maven repository and the SDK dependency to your project.
Project-level settings.gradle (or build.gradle):
Ensure google() and mavenCentral() are present.
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "My Application"
include(":app")
2. App-level build.gradle:
Add the implementation line to your dependencies block.
* Never use wild card characters while adding dependencies in gradle files.
dependencies {
implementation 'com.google.android.gms:play-services-ads:23.0.0'
// Use latest version
// If you are planning to use other ad sources Please add these at this steps.
// If you do not want to add additional sdk sources then don't add below dependencies.
implementation("com.google.ads.mediation:fyber:8.4.3.0")
implementation("com.google.ads.mediation:inmobi:11.1.1.0")
implementation("com.google.ads.mediation:facebook:6.21.0.1")
}More on adding additional ad sources can be found here.
3. Add your Ad Manager app ID
Add your Ad Manager app ID, as identified in the Ad Manager web interface, to your app's AndroidManifest.xml file
<manifest>
<application>
<!-- Sample Ad Manager app ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="your_APP_ID"/>
</application>
</manifest>4. Compile the app
Compile the app at this step to check if there are any errors. If the app is compiled successfully, proceed with SDK initialization and banner / MREC integrations.
5. SDK initialization
Before loading ads, initialize Google Mobile Ads SDK by calling MobileAds.initialize().
This method initializes the SDK and calls a completion listener once both Google Mobile Ads SDK and adapter initializations have completed, or after a 30-second timeout. This needs to be done only once, ideally at app launch.
If you're using mediation, wait until the completion handler is called before loading ads. This ensures that all mediation adapters are initialized.
Ads may be preloaded by Google Mobile Ads SDK or mediation partner SDKs upon initialization. If you need to obtain consent from users in the European Economic Area (EEA), set any request-specific flags, such as setTagForChildDirectedTreatment() or setTagForUnderAgeOfConsent(), or otherwise take action before loading ads, ensure you do so before initializing Google Mobile Ads SDK.
Initialize the SDK once, ideally in the onCreate method of your main Activity or Application class.
// [START initialize_sdk]
CoroutineScope(Dispatchers.IO).launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MyActivity) {}
// [START_EXCLUDE silent]
runOnUiThread {
// Load an ad on the main thread.
loadBanner()
}
// [END_EXCLUDE]
}
// [END initialize_sdk]
}Google Mobile sdk sample apps (Android) link here.
Setup Banner ads
Document: https://developers.google.com/ad-manager/mobile-ads-sdk/android/banner
Sample app: https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admanager/BannerExample
XML Layout:
Add a view to your layout XML file to serve as the container for your anchored adaptive banner ad:
<!-- Ad view container that fills the width of the screen and adjusts its
height to the content of the ad. -->
<FrameLayout
android:id="@+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />
Set the AdSize to an anchored adaptive banner type with a specified width:
// Request a large anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getLargeAnchoredAdaptiveBannerAdSize(this, 360))Sample link can be found here.
Create an AdManagerAdView using the ad size to add to your app's layout:
// Create a new ad view.
val adView = AdManagerAdView(this)
adView.adUnitId = AD_UNIT_ID
// Request a large anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getLargeAnchoredAdaptiveBannerAdSize(this, 360))
this.adView = adView
// Replace ad container with new ad view.
binding.adViewContainer.removeAllViews()
binding.adViewContainer.addView(adView)
The following example loads a 360-width anchored adaptive banner ad into an AdManagerAdView object:
val adRequest = AdManagerAdRequest.Builder().build()
adView.loadAd(adRequest)
If you configured your ad unit to refresh, you don't need to request another ad when the ad fails to load. Google Mobile Ads SDK respects any refresh rate you specified in the Ad Manager UI. If you haven't enabled refresh, issue a new request. For more details on ad unit refresh, such as setting a refresh rate, see Refresh rate for ads in mobile apps.
When you are finished using a banner ad, you can release the banner ad's resources.
To release the ad's resource, you remove the ad from the view hierarchy and drop all its references:
fun destroyBanner() {
// Remove banner from view hierarchy.
val parentView = adView?.parent
if (parentView is ViewGroup) {
parentView.removeView(adView)
}
// Destroy the banner ad resources.
adView?.destroy()
// Drop reference to the banner ad.
adView = null
}
You can listen for a number of events in the ad's lifecycle, including loading, ad impression, and click, as well as ad open and close events. It is recommended to set the callback before loading the banner.
adView?.adListener =
object : AdListener() {
override fun onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
override fun onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
override fun onAdFailedToLoad(adError: LoadAdError) {
// Code to be executed when an ad request fails.
}
override fun onAdImpression() {
// Code to be executed when an impression is recorded
// for an ad.
}
override fun onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
override fun onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
}
Hardware acceleration is enabled by default, but some apps may choose to disable it. If this applies to your app, we recommend enabling hardware acceleration for Activity classes that use ads.
If your app does not behave properly with hardware acceleration turned on globally, you can control it for individual activities as well. To enable or disable hardware acceleration, you can use the android:hardwareAccelerated attribute for the <application> and <activity> elements in your AndroidManifest.xml. The following example enables hardware acceleration for the entire app but disables it for one activity:
<application android:hardwareAccelerated="true">
<!-- For activities that use ads, hardwareAcceleration should be true. -->
<activity android:hardwareAccelerated="true" />
<!-- For activities that don't use ads, hardwareAcceleration can be false. -->
<activity android:hardwareAccelerated="false" />
</application>
For other banner types implementation, please check the links below.
Collapsible banner ads
https://developers.google.com/ad-manager/mobile-ads-sdk/android/banner/collapsible
For inline adaptive banner implementation, please follow the guide below.
https://developers.google.com/ad-manager/mobile-ads-sdk/android/banner/inline-adaptive
To create an inline adaptive ad size, complete the following:
- Get the width of the device in use, or set your own width if you don't want to use the full width of the screen.
private val adWidth: Int
get() {
val displayMetrics = resources.displayMetrics
val adWidthPixels =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics: WindowMetrics = this.windowManager.currentWindowMetrics
windowMetrics.bounds.width()
} else {
displayMetrics.widthPixels
}
val density = displayMetrics.density
return (adWidthPixels / density).toInt()
}Sample app link:
- To get an inline adaptive ad size object for the chosen orientation, use a static method on the ad size class:
val adView = AdView(this@MainActivity)
adView.setAdSize(AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(this, adWidth))
When implementing adaptive banners in your app, note these points:
- The inline adaptive banner sizes work best when using the full available width. In most cases, this size is the full width of the device screen in use, or the full width of the banner's parent content. You must know the width of the view to place in the ad, the device width, the parent content width, and applicable safe areas.
- You may need to update or create new line items to work with adaptive sizes.
https://support.google.com/admanager/answer/9464128
To preload an inline adaptive banner ad for a specific orientation, use the following methods:
AdSize.getPortraitInlineAdaptiveBannerAdSize(Context context, int width)AdSize.getLandscapeInlineAdaptiveBannerAdSize(Context context, int width)
If your app supports both portrait and landscape views, and you want to preload an adaptive banner ad in the current orientation,
use AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(Context context, int width) This method loads an ad in the current orientation.
By default, inline adaptive banners instantiated without a maxHeight value have a maxHeight equal to the device height. To limit the inline adaptive banner height, use the AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight) method.
|
IMPORTANT: If you run into any issues during integration or require any further assistance, Please don’t hesitate to contact the Freestar support team for assistance. |
Once you complete the integration, share the apk file along with ad unit ids implemented for further verification.