-
Notifications
You must be signed in to change notification settings - Fork 4
Interstitial Ads
The AdManageKit library (version v1.3.2) provides robust management of interstitial ads through the AdManager class in the com.i2hammad.admanagekit.admob package. Interstitial ads are full-screen ads displayed at natural transition points in your app, such as between activities or during pauses in gameplay. The AdManager singleton supports loading, caching, and displaying interstitial ads with flexible options like time-based or count-based triggers, dialog support, and Firebase Analytics integration for tracking ad events.
Library Version: v1.3.2
Last Updated: May 22, 2025
- Ad Loading and Caching: Load interstitial ads and cache them for later use, with automatic reload after display.
-
Flexible Display Options:
- Immediate display with or without a loading dialog.
- Time-based display (e.g., show every 15 seconds).
- Count-based display (e.g., show up to a maximum number of times).
-
Purchase Check: Automatically skips ad display if the user has purchased the app (via
BillingConfig). - Firebase Analytics: Logs ad impressions, paid events, failures, and dismissals.
- Dialog Support: Optional loading dialog to improve user experience during ad display.
The AdManager singleton manages interstitial ads:
-
Key Methods:
-
loadInterstitialAd(context: Context, adUnitId: String): Loads an interstitial ad for later use. -
loadInterstitialAd(context: Context, adUnitId: String, callback: InterstitialAdLoadCallback): Loads an ad with a custom callback. -
forceShowInterstitial(activity: Activity, callback: AdManagerCallback): Displays an ad immediately. -
forceShowInterstitialWithDialog(activity: Activity, callback: AdManagerCallback, isReload: Boolean): Displays an ad with a loading dialog. -
showInterstitialAdByTime(activity: Activity, callback: AdManagerCallback): Displays an ad if the time interval has elapsed. -
showInterstitialAdByCount(activity: Activity, callback: AdManagerCallback, maxDisplayCount: Int): Displays an ad if the display count is below the limit. -
isReady(): Boolean: Checks if an ad is loaded and ready to display. -
setAdInterval(intervalMillis: Long): Sets the minimum time interval between ad displays. -
setAdDisplayCount(count: Int): Sets the current ad display count.
-
-
Configuration:
- Default ad interval: 15 seconds (
adIntervalMillis). - Tracks display count (
adDisplayCount) and last ad show time (lastAdShowTime).
- Default ad interval: 15 seconds (
-
Callbacks:
- Uses
AdManagerCallbackfor handling ad dismissal (onNextAction) and other events. - Supports
InterstitialAdLoadCallbackfor custom load handling.
- Uses
Add AdManageKit v1.3.2 to your project via Gradle:
implementation 'com.github.i2hammad.AdManageKit:ad-manage-kit:1.3.2'
implementation 'com.github.i2hammad.AdManageKit:ad-manage-kit-billing:1.3.2'Ensure dependencies are included:
- Google AdMob SDK
- Firebase Analytics
- Material Components (for loading dialogs)
- Project resources (
BillingConfig)
Load an interstitial ad to cache it for later display:
AdManager.getInstance().loadInterstitialAd(this, "ca-app-pub-3940256099942544/1033173712")Load with a custom callback:
AdManager.getInstance().loadInterstitialAd(this, "ca-app-pub-3940256099942544/1033173712", object : InterstitialAdLoadCallback() {
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d("AdManager", "Interstitial ad loaded")
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
Log.e("AdManager", "Failed to load: ${loadAdError.message}")
}
})Show an ad immediately:
AdManager.getInstance().forceShowInterstitial(this, object : AdManagerCallback() {
override fun onNextAction() {
startActivity(Intent(this@CurrentActivity, NextActivity::class.java))
}
})Show an ad with a 500ms loading dialog:
AdManager.getInstance().forceShowInterstitialWithDialog(this, object : AdManagerCallback() {
override fun onNextAction() {
startActivity(Intent(this@CurrentActivity, NextActivity::class.java))
}
})Show an ad if at least 15 seconds have passed since the last ad (configurable via setAdInterval):
AdManager.getInstance().setAdInterval(30_000) // 30 seconds
AdManager.getInstance().showInterstitialAdByTime(this, object : AdManagerCallback() {
override fun onNextAction() {
startActivity(Intent(this@CurrentActivity, NextActivity::class.java))
}
})Show an ad up to a maximum number of times:
AdManager.getInstance().showInterstitialAdByCount(this, object : AdManagerCallback() {
override fun onNextAction() {
startActivity(Intent(this@CurrentActivity, NextActivity::class.java))
}, maxDisplayCount = 3)Verify if an ad is ready to display:
if (AdManager.getInstance().isReady()) {
Log.d("AdManager", "Interstitial ad is ready")
} else {
Log.d("AdManager", "No interstitial ad available")
}Set a custom time interval:
AdManager.getInstance().setAdInterval(60_000) // 60 secondsSet or reset the display count:
AdManager.getInstance().setAdDisplayCount(0) // Reset count-
Loading:
-
loadInterstitialAdinitiates an ad request usingInterstitialAd.load. - The ad is cached in
mInterstitialAdif loaded successfully. - If the user has purchased the app (
BillingConfig.getPurchaseProvider().isPurchased()), loading is skipped.
-
-
Error Handling:
- Failed loads are logged to Firebase Analytics with the ad unit ID and error code.
- Custom errors are triggered for purchased apps (
PURCHASED_APP_ERROR_CODE).
-
Callbacks:
-
InterstitialAdLoadCallbackhandles load success or failure. -
AdManagerCallbackensures the app proceeds (onNextAction) after ad display or failure.
-
-
Display Check:
-
isReady()verifies a loaded ad exists and the user hasn’t purchased the app. - Time-based display checks if
adIntervalMillishas elapsed sincelastAdShowTime. - Count-based display checks if
adDisplayCountis belowmaxDisplayCount.
-
-
Dialog Support:
-
forceShowInterstitialWithDialogshows a non-cancelable Material AlertDialog for 500ms before displaying the ad.
-
-
Ad Events:
-
FullScreenContentCallbackhandles ad show, dismissal, and failure events. -
OnPaidEventListenerlogs revenue data to Firebase Analytics. - Analytics events include impressions (
AD_IMPRESSION), dismissals (ad_dismissed), and failures (ad_failed_to_show).
-
-
Reload:
- By default, a new ad is loaded after display (
reloadAd = true), ensuring availability for future displays.
- By default, a new ad is loaded after display (
fun loadInterstitialAd(context: Context, adUnitId: String) {
this.adUnitId = adUnitId
initializeFirebase(context)
val adRequest = AdRequest.Builder().build()
isAdLoading = true
InterstitialAd.load(context, adUnitId, adRequest, object : InterstitialAdLoadCallback() {
override fun onAdLoaded(interstitialAd: InterstitialAd) {
mInterstitialAd = interstitialAd
isAdLoading = false
Log.d("AdManager", "Interstitial ad loaded")
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
Log.e("AdManager", "Failed to load interstitial ad: ${loadAdError.message}")
isAdLoading = false
mInterstitialAd = null
val params = Bundle().apply {
putString(FirebaseAnalytics.Param.AD_UNIT_NAME, adUnitId)
putString("ad_error_code", loadAdError.code.toString())
}
firebaseAnalytics.logEvent("ad_failed_to_load", params)
}
})
}
fun forceShowInterstitial(activity: Activity, callback: AdManagerCallback) {
showAd(activity, callback, true)
}-
Purchase Integration: Ensure
BillingConfig.setPurchaseProvideris called in yourApplicationclass to respect in-app purchases. -
Ad Frequency: Use
setAdIntervalorshowInterstitialAdByCountto avoid overwhelming users with frequent ads. -
Dialog Usage: Use
forceShowInterstitialWithDialogfor smoother transitions in critical flows (e.g., activity changes). -
Error Handling: Implement
AdManagerCallbackandInterstitialAdLoadCallbackto handle load/display failures gracefully. -
Testing:
- Test with AdMob test IDs (e.g.,
ca-app-pub-3940256099942544/1033173712). - Verify time-based and count-based triggers.
- Test purchase scenarios to ensure ads are skipped for premium users.
- Test with AdMob test IDs (e.g.,
- Analytics: Review Firebase Analytics logs to monitor ad performance and errors.
-
Single Ad Cache: Only one interstitial ad is cached at a time per
AdManagerinstance. -
Manual Frequency Control: Time and count limits are managed manually; adjust
adIntervalMillisormaxDisplayCountas needed. - Dialog Dependency: The loading dialog requires Material Components; ensure it’s included in your app.
- Google AdMob SDK: For ad loading and display.
- Firebase Analytics: For logging ad events.
- Material Components: For loading dialogs.
-
Project Resources:
BillingConfigfor purchase checks.
-
Ad Not Loading: Verify
adUnitId, network connectivity, and AdMob configuration. -
Ad Not Displaying: Check
isReady()and ensure the user hasn’t purchased the app. - Dialog Issues: Ensure Material Components are included and the activity isn’t finishing.
- Analytics Missing: Confirm Firebase is initialized and configured.
- Support for preloading multiple interstitial ads.
- Configurable dialog duration and styling.
- Automatic frequency optimization based on user engagement.
AdManageKit v3.3.4 | GitHub | API Docs | Report Issue | Buy me a coffee