Skip to content

Android Banner Ad Integration

Overview

Banner ads are rectangular ads displayed at the top or bottom of an app screen, with the following characteristics:

  • Small footprint, does not affect user experience
  • Continuous display, improving ad exposure
  • Fast loading and responsive
  • Suitable for various app scenarios

Integration Steps

Refer to the BannerAdHelper in the demo.

1. Initialize the Ad

Load a banner ad in an Activity or Fragment:

kotlin
/**
 * Banner Ad Helper
 *
 * Responsible for banner ad loading, display, and lifecycle management
 *
 * @param activity Context Activity
 * @param logger Log printing tool
 */
class BannerAdHelper(private val activity: Activity, private val logger: PrintLogger) {

    /**
     * Banner ad object
     *
     * Created via UjuAdObject factory method, used to manage banner ad loading, display, and destruction
     */
    private var bannerAd: UjuAdObject? = null

    /**
     * Load a banner ad
     *
     * This method creates an ad config, initializes the banner ad object via the UjuAdObject.getBannerObject() factory method,
     * sets the ad listener, and finally calls load() to start loading the ad
     */
    fun load() {
        // Create the ad config object, set the placement ID, ad size, and optional display scenario key
        val adConfig = UjuAdConfig(
            placementId = DemoConfig.BANNER_ID, // Banner placement ID
            adViewSize = AdViewSize(width = 320, height = 100), // Ad size: 320x100, only effective for template rendering
            scenarioKey = "banner_scene" // Optional: tracks ad display scenario
        )

        // Create the banner ad object via the factory method
        bannerAd = UjuAdObject.getBannerObject(activity, adConfig)

        // Set the ad listener to monitor various ad events
        bannerAd?.setAdObjectListener(object : FeedAdObjectListener {
            /**
             * Ad load success callback
             *
             * @param placementId Placement ID
             */
            override fun onLoadSuccess(placementId: String) {
                // Ad loaded successfully, can now display; recommend checking isReady before showing
                logger.add("Banner: onLoadSuccess")
            }

            /**
             * Ad load failure callback
             *
             * @param error Error information
             * @param placementId Placement ID
             */
            override fun onLoadError(
                error: UjuException,
                placementId: String
            ) {
                // Log the load error
                logger.add("Banner: onLoadError:${error.message}")
            }

            /**
             * Ad display error callback
             *
             * @param error Error information
             */
            override fun onAdError(
                error: UjuException
            ) {
                // Log the ad display error
                logger.add("Banner: onAdError:${error.message}")
            }

            /**
             * Ad display success callback
             */
            override fun onAdShow() {
                // Get ad info, log the ecpm value
                val ecpm = bannerAd?.getAdInfo()?.ecpm
                logger.add("Banner: onAdShow: ecpm:$ecpm")
            }

            /**
             * Ad clicked callback
             */
            override fun onAdClicked() {
                // Log the ad click event
                logger.add("Banner: onAdClicked")
            }

            /**
             * Ad closed callback
             */
            override fun onAdClosed() {
                // Log the ad close event
                logger.add("Banner: onAdClosed")
            }

            /**
             * Ad landing page closed callback
             */
            override fun onLpClosed() {
                // Log the landing page close event
                logger.add("Banner: onLpClosed")
            }
        })

        // Start loading the ad
        bannerAd?.load()
        // Log the load ad event
        logger.add("Banner: load, placementId:${adConfig.placementId}")
    }

    /**
     * Display the banner ad
     *
     * Before displaying, checks whether the ad is ready
     * Only calls show() when the ad state is ready
     *
     * @param viewGroup ViewGroup to hold the ad
     */
    fun show(viewGroup: ViewGroup) {
        // Check if the ad is ready
        if (bannerAd?.isReady() == true) {
            // Ad is ready, display it in the specified ViewGroup
            bannerAd?.show(activity, viewGroup)
        } else {
            // Ad not ready, log it
            logger.add("Banner: ad not ready")
        }
    }

    /**
     * Check if the ad is loaded
     *
     * @return true means the ad object has been created, false means not created
     * Note: This method only checks whether the ad object exists, not whether it is ready
     * To check if the ad can be displayed, use the isReady() method
     */
    fun isLoaded(): Boolean {
        return bannerAd != null
    }

    /**
     * Destroy the ad object
     *
     * Call this method when the ad is no longer needed to destroy the ad object and release resources
     */
    fun destroy() {
        // Destroy the ad object
        bannerAd?.destroy()
        // Null out the ad object reference
        bannerAd = null
    }
}

UjuAdConfig Configuration

ParameterTypeRequiredDescription
placementIdStringYesPlacement ID
adViewSizeAdViewSizeNoAd size, specifies width/height (unit: dp), only effective for template rendering, default AdViewSize() (width=screen width dp, height=200)
scenarioKeyStringNoAd display scenario key, used for scenario statistics
userIdStringNoUser ID, for personalized strategy
customDataMap<String, String>NoCustom data, passed through to the ad server

Ad Sizes

The UjuAd SDK supports the following banner ad sizes:

Size TypeWidth x HeightDescriptionApplicable Scene
BANNER320x50Standard bannerMobile apps
LARGE_BANNER320x100Large bannerNeeds more display space
MEDIUM_RECTANGLE300x250Medium rectangleContent pages
FULL_BANNER468x60Full-size bannerTablet devices
LEADERBOARD728x90Leaderboard bannerTablet or desktop devices
SMART_BANNERAdaptiveSmart bannerAuto-fits screen width

Best Practices

1. Ad Placement

  • Bottom placement: Most common position, does not block main content
  • Top placement: Suitable for specific app scenarios
  • Between content: Interleaved in long articles or lists

2. Optimization Tips

  • Set a reasonable refresh interval: 30-60 seconds recommended, avoid overly frequent refreshes
  • Preload ads: Load ads before they need to be displayed
  • Handle network status: Adjust loading strategy on poor networks
  • Test different sizes: Choose the right ad size for your app UI

3. Pitfalls to Avoid

  • Do not place multiple banner ads on the same screen
  • Do not block core app features
  • Do not place ads in areas with frequent user interaction
  • Do not set refresh intervals too short

FAQ

Q: Why is the banner ad not showing?

A: Possible reasons:

  • Incorrect placement ID
  • Network connection issue
  • Insufficient ad inventory
  • Layout issue (container not visible or size is 0)
  • Improper refresh interval

Q: How to improve banner ad click-through rate?

A: Recommendations:

  • Choose an appropriate ad position
  • Ensure ads are relevant to app content
  • Use an appropriate ad size
  • Avoid ad occlusion
  • Optimize app user experience

Q: Can banner ads be used in RecyclerView?

A: Yes, but note:

  • Manage ad views in the ViewHolder
  • Properly handle the ad lifecycle
  • Avoid frequently creating and destroying ad views