Skip to content

Android API Reference

This document is the API reference manual for the UjuAd Android SDK, covering all public enums and complete signatures of core classes. All content is verified against the SDK source code for developers to consult during integration.

Reading Guide

  • For first-time integration, read SDK Initialization and Preparation first.
  • For specific usage of each ad type, refer to the Ad Type Integration series.
  • This document only lists API signatures and field meanings, not complete integration examples.

Enum Reference

FeedType

Feed ad rendering type, used to distinguish banner, template feed, and self-rendering feed.

Enum ValueMeaning
BANNERBanner ad, rendered internally by the SDK and bound to a container
EXPRESSTemplate feed, rendered using platform-provided templates
UNIFIEDSelf-rendering feed, developers draw the ad view themselves
kotlin
// Get the rendering type of the current ad object
val feedType = adObject.getFeedType()
when (feedType) {
    FeedType.BANNER -> {
        // Banner ad, call show(activity, viewGroup) to display
    }
    FeedType.EXPRESS -> {
        // Template rendering, call show(activity, viewGroup) to display
    }
    FeedType.UNIFIED -> {
        // Self-rendering, call getAdData() to get creatives and bind views manually
    }
    else -> {
        // Unknown type, handle with null-safety protection
    }
}

AdMediaType

Media creative type for self-rendering ads, used to determine if the creative is single image, multi image, or video.

Enum ValueValueMeaning
SINGLE_IMAGE1Single image creative
MULTI_IMAGE2Multi image creative (image group)
VIDEO3Video creative
kotlin
// Choose different rendering layouts based on media type
val data = adObject.getAdData()
data?.let { adData ->
    when (adData.mediaType) {
        AdMediaType.SINGLE_IMAGE -> {
            // Single image layout, load image using imageUrl
        }
        AdMediaType.MULTI_IMAGE -> {
            // Multi image layout, load image group using imageUrlList
        }
        AdMediaType.VIDEO -> {
            // Video layout, requires mediaViewId to host video playback
        }
    }
}

AdBidType

Ad bidding type, identifies the bidding mode of the ad placement.

Enum ValueValueMeaning
NORMAL1Waterfall mode, requests in priority order
ADX2SDK internal bidding mode
C2S3Client-to-Server bidding
S2S4Server-to-Server bidding

AdPlatformType

Ad platform identifier enum, used to identify the ADN platform of the ad source.

Enum ValueValuePlatform NameDescription
CSJ1PangleByteDance Pangle
YLH2YLHTencent YLH (GDT)
BD3BaiduBaidu BaiQingTeng
KS4KuaishouKuaishou Ads
VIVO13VIVOVIVO Ad Platform
OPPO14OPPOOPPO Ad Platform

ADX Self-Owned Ad Sources

The SDK has built-in ADX self-owned ad sources (auto-enabled after importing uju-ad-adx). The internal DSP platform identifiers are SDK implementation details and developers do not need to concern themselves with them. The platform ID obtained via UjuAdInfo.platformId for ADX ads is uniformly 100.

kotlin
// Determine the ad source platform via platformId
val adInfo = adObject.getAdInfo()
adInfo?.let { info ->
    val platform = AdPlatformType.fromValue(info.platformId)
    // platform is the ad source platform enum
}

UjuAdInitStatus

SDK initialization status enum, available via UjuAdSdk.getInitializeState().

Enum ValueMeaning
IDLEIdle state, start() not yet called
INITIALIZINGInitializing, collecting device info and pulling strategy
INITIALIZEDInitialized, ads can be loaded normally
INITIALIZATION_FAILEDInitialization failed
kotlin
// Check SDK initialization status
when (UjuAdSdk.getInitializeState()) {
    UjuAdInitStatus.IDLE -> {
        // Not started yet, need to call UjuAdSdk.start()
    }
    UjuAdInitStatus.INITIALIZING -> {
        // Initializing, please wait
    }
    UjuAdInitStatus.INITIALIZED -> {
        // Initialization complete, ads can be loaded
    }
    UjuAdInitStatus.INITIALIZATION_FAILED -> {
        // Initialization failed, troubleshoot and retry
    }
}

CurrencyType

Currency type enum, identifies the settlement currency of the ad platform.

Enum ValueMeaning
CNYChinese Yuan (RMB)
USDUS Dollar

EcpmType

eCPM unit type enum, identifies the price unit returned by the ad platform.

Enum ValueMeaning
YUANYuan
CENTCent

Conversion Notes

Some platforms (e.g., YLH) return eCPM in "cents"; the SDK internally converts to "yuan" based on EcpmType for unified output.

Public API Reference

UjuAdSdk

SDK global entry, an object singleton. Responsible for SDK initialization, startup, status query, and resource release.

Method List

Method SignatureReturn ValueDescription
init(context: Context, config: UjuAdInitConfig)UnitPhase 1 initialization, lightweight operation, does not collect privacy info. Pass Application context and init config
start(listener: BaseInitListener)UnitPhase 2 startup, collects device info and pulls strategy, calls back listener on completion
isSdkInitialized()BooleanDetermines if init is complete (only checks init, not whether start succeeded)
getVersion()StringGets the current SDK version number
getOAID()StringGets OAID (returns empty string if not obtained)
getGoogleAdId()StringGets Google Advertising ID (returns empty string if not obtained)
getInitializeState()UjuAdInitStatusGets the SDK initialization status enum
getAppId()StringGets the current App ID
updateChannel(channel: String, subChannel: String)UnitUpdates channel and sub-channel info for stats and revenue sharing
destroy()UnitReleases SDK resources, released in reverse initialization order
kotlin
// Phase 1: init (lightweight, does not collect privacy)
UjuAdSdk.init(application, config)

// Phase 2: start SDK and listen for callback
UjuAdSdk.start(object : BaseInitListener {
    override fun onInitSuccess() {
        // Initialization successful, can start loading ads
    }

    override fun onInitFailed(error: UjuException) {
        // Initialization failed, log the error
        Log.e("UjuAd", "Init failed: ${error.message}")
    }
})

// Check if init is complete
if (UjuAdSdk.isSdkInitialized()) {
    // init complete, can call start
}

// Get SDK version
val version = UjuAdSdk.getVersion()

// Update channel info
UjuAdSdk.updateChannel("new_channel", "new_sub_channel")

// Release resources (usually called on app exit)
UjuAdSdk.destroy()

Two-Phase Initialization

init() only saves config and does not perform any time-consuming operations; start() actually collects device info, pulls strategy, and initializes adapters. You must call init() first, then start().

UjuAdObject

Unified ad object, created via static factory methods, carries the ad's load, show, destroy lifecycle.

Factory Methods (Static)

Method SignatureDescription
getBannerObject(activity: Activity, adConfig: UjuAdConfig): UjuAdObjectCreates a banner ad object
getSplashObject(activity: Activity, adConfig: UjuAdConfig): UjuAdObjectCreates a splash ad object
getNativeObject(activity: Activity, adConfig: UjuAdConfig): UjuAdObjectCreates a native/feed ad object
getInterstitialObject(activity: Activity, adConfig: UjuAdConfig): UjuAdObjectCreates an interstitial ad object
getRewardObject(activity: Activity, adConfig: UjuAdConfig): UjuAdObjectCreates a rewarded video ad object

Instance Methods

Method SignatureReturn ValueDescription
setAdObjectListener(listener)UnitSets the ad listener; listener type must match the ad type
load()UnitLoads the ad, triggers bidding and request flow
show(activity: Activity)UnitShows the ad (no container), for rewarded video, interstitial
show(activity: Activity, viewGroup: ViewGroup)UnitShows the ad (requires container), for splash, banner, native template
isReady()BooleanDetermines if the ad is ready to show
destroy()UnitDestroys the ad object, releases resources
getAdInfo()UjuAdInfo?Gets ad info (price, platform, etc.), returns null if not loaded
getFeedType()FeedType?Gets the feed rendering type (only valid for native/banner)
getAdData()NativeAdData?Gets self-rendering native ad creative data (only valid for self-rendering)
registerViewForInteraction(activity, adView, viewGroup, binder)UnitRegisters self-rendering ad view, binds click interaction and creatives

No pause/resume Methods

UjuAdObject does not have pause() and resume() methods. To pause display, call destroy() to destroy and recreate the object.

kotlin
// Create a rewarded video ad object
val rewardAd = UjuAdObject.getRewardObject(activity, adConfig)

// Set listener
rewardAd.setAdObjectListener(object : RewardAdObjectListener {
    override fun onLoadSuccess(placementId: String) {
        // Ad loaded successfully
    }

    override fun onLoadError(error: UjuException, placementId: String) {
        // Ad load failed
    }

    override fun onAdShow() {
        // Ad displayed
    }

    override fun onAdError(error: UjuException) {
        // Ad display error (note: only 1 parameter)
    }

    override fun onAdPlayComplete() {
        // Video playback complete
    }

    override fun onAdClicked() {
        // Ad clicked
    }

    override fun onAdSkippedVideo() {
        // User skipped video
    }

    override fun onAdRewardArrived() {
        // Grant reward (note: no parameters, no RewardItem)
    }

    override fun onAdClosed() {
        // Ad closed
    }
})

// Load ad
rewardAd.load()

// Check if ready before showing
if (rewardAd.isReady()) {
    rewardAd.show(activity)
}

UjuAdInitConfig

SDK initialization config, data class.

Constructor Parameters

ParameterTypeRequiredDefaultDescription
appIdStringYesApp ID, obtained from the UjuAd backend
appKeyStringYesRSA public key, obtained from backend, pass as-is
channelStringYesChannel identifier for stats and revenue sharing (no default)
subChannelStringNo""Sub-channel
isDebugBooleanNofalseDebug mode, recommended to enable during development
wxAppIdStringNo""WeChat AppId, for WeChat ad channels
presetStrategyFileNameString?NoPreset strategy filename, e.g., "placement_config.json"
privacyConfigUjuPrivacyConfig?NoPrivacy config
personalizationUjuPersonalizedConfig?NoPersonalization config
kotlin
// Create init config
val config = UjuAdInitConfig(
    appId = "YOUR_APP_ID",                       // Required, App ID
    appKey = "YOUR_APP_KEY",                     // Required, RSA public key
    channel = "main_channel",                    // Required, channel identifier
    subChannel = "sub_channel",                  // Optional, sub-channel
    isDebug = BuildConfig.DEBUG,                 // Optional, debug mode
    wxAppId = "wx_xxxxx",                        // Optional, WeChat AppId
    presetStrategyFileName = "strategy.json",    // Optional, preset strategy file
    privacyConfig = UjuPrivacyConfig(            // Optional, privacy config
        androidId = getAndroidId(context)
    ),
    personalization = UjuPersonalizedConfig(     // Optional, personalization config
        userId = "user_001",
        userAge = 25
    )
)

UjuAdConfig

Ad request config, data class. Passed in when creating each ad object.

Fields

FieldTypeRequiredDefaultDescription
placementIdStringYesPlacement ID
scenarioKeyString?NoScenario identifier for stats
adViewSizeAdViewSizeNoAdViewSize()Ad size, only required for template rendering (banner/native)
adFormatInt?NoAd format
userIdString?NoUser ID, commonly used for rewarded video
customDataMap<String, String>?NoCustom data
kotlin
// Create ad config
val adConfig = UjuAdConfig(
    placementId = "YOUR_PLACEMENT_ID",           // Required, placement ID
    scenarioKey = "reward_scene",                // Optional, scenario identifier
    userId = "user_001",                         // Optional, user ID (commonly used for rewarded video)
    customData = mapOf("key" to "value")         // Optional, custom data
)

UjuPrivacyConfig

Privacy config, data class. Developers can proactively pass device identifiers; once passed, the SDK will use the provided identifiers and not actively collect them. Also controls which types of information the SDK is allowed to collect.

Fields

FieldTypeRequiredDefaultDescription
useLocationBooleanNotrueWhether to allow SDK to use geographic location
useAppListBooleanNotrueWhether to allow SDK to read app list
usePhoneStateBooleanNotrueWhether to allow SDK to read phone state
useWifiStateBooleanNotrueWhether to allow SDK to read WiFi state
imeiString?NonullIMEI, proactively passed by developer
macAddressString?NonullMAC address, proactively passed by developer
oaidString?NonullOAID, proactively passed by developer
androidIdString?NonullAndroidId, proactively passed by developer
kotlin
// Create privacy config
val privacyConfig = UjuPrivacyConfig(
    androidId = getAndroidId(context),           // Pass AndroidId
    oaid = UjuAdSdk.getOAID(),                   // Pass OAID
    useLocation = true,                          // Allow use of location
    useAppList = false                           // Disable app list reading (as needed)
)

Privacy Compliance

Proactively passing device identifiers (e.g., AndroidId, OAID) via UjuPrivacyConfig helps meet privacy compliance requirements. Developers should obtain user consent before passing relevant identifiers. Use useLocation/useAppList/usePhoneState/useWifiState to control the SDK's information collection scope.

UjuPersonalizedConfig

Personalization config, data class. Used to provide user-related data to support personalized ad strategies.

Fields

FieldTypeRequiredDefaultDescription
userIdStringYesUnique user identifier
userAgeIntYesUser age
userGenderIntNo0Gender: 0 unknown / 1 male / 2 female
userKeywordsList<String>NoemptyList()User tag keywords, e.g., ["game", "sports"]
kotlin
// Create personalization config
val personalization = UjuPersonalizedConfig(
    userId = "user_001",                         // Unique user identifier
    userAge = 25,                                // User age
    userGender = 1,                              // Gender: 1 male / 2 female / 0 unknown
    userKeywords = listOf("game", "sports")      // User tag keywords
)

UjuAdInfo

Ad info model, data class. Obtained via UjuAdObject.getAdInfo().

Fields

FieldTypeDescription
ecpmDoubleAd price (eCPM, unit: yuan)
placementIdStringPlacement ID
soltIdStringPlacement slot ID (note: source code spelling is soltId)
platformIdIntPlatform ID, corresponds to AdPlatformType value
adFormatAdFormatAd type

Field Spelling Note

The slot ID field in UjuAdInfo is spelled soltId (not slotId); this is the actual spelling in the source code, please keep it consistent when using.

kotlin
// Get ad info
val adInfo = adObject.getAdInfo()
adInfo?.let { info ->
    // Get eCPM price (unit: yuan)
    val ecpm = info.ecpm
    // Get placement ID
    val placementId = info.placementId
    // Get platform ID
    val platformId = info.platformId
}

NativeAdData

Native ad self-rendering creative data, data class. Obtained via UjuAdObject.getAdData().

Fields

FieldTypeDescription
titleString?Ad title (short text)
descString?Ad description (long text)
sourceString?Ad source (e.g., advertiser name)
iconUrlString?Icon image URL
mediaTypeAdMediaTypeMedia type, default SINGLE_IMAGE
imageUrlString?Main image URL
imageUrlListList<String>?Multi image URL list
callToActionString?Call-to-action text (e.g., "Download Now", "View Details")
kotlin
// Get self-rendering creative data
val adData = adObject.getAdData()
adData?.let { data ->
    // Fill title and description
    titleView.text = data.title ?: ""            // Null-safety protection
    descView.text = data.desc ?: ""
    sourceView.text = data.source ?: ""
    // Call-to-action button
    ctaButton.text = data.callToAction ?: "View Details"
    // Load image or video based on mediaType
    when (data.mediaType) {
        AdMediaType.VIDEO -> {
            // Video creative, play using mediaViewId
        }
        AdMediaType.MULTI_IMAGE -> {
            // Multi image creative, load using imageUrlList
        }
        else -> {
            // Single image creative, load using imageUrl
        }
    }
}

NativeAdViewBinder

Native ad view binder, data class. Used to bind control IDs in the self-rendering layout to ad creative fields.

Fields

FieldTypeDescription
titleIdInt?Title control ID
descIdInt?Description control ID
sourceIdInt?Ad source control ID
iconIdInt?Small image (Icon) control ID
imageIdInt?Large image control ID
imageViewsList<ImageView>?ImageView control list, required when custom layout includes images
mediaViewIdInt?Video control ID, required when custom layout includes video
callToActionIdInt?Button control ID
logoLayoutIdInt?Logo layout ID
clickViewsIdsList<Int>?Optional, specifies the list of clickable control IDs (defaults to full-area click if not passed)
dislikeIdInt?Optional, dislike button control ID
kotlin
// Create view binder
val binder = NativeAdViewBinder(
    titleId = R.id.tv_ad_title,                  // Title control ID
    descId = R.id.tv_ad_desc,                    // Description control ID
    sourceId = R.id.tv_ad_source,                // Source control ID
    iconId = R.id.iv_ad_icon,                    // Icon control ID
    imageId = R.id.iv_ad_image,                  // Large image control ID
    mediaViewId = R.id.mv_ad_media,              // Video control ID
    callToActionId = R.id.btn_ad_cta,            // Button control ID
    logoLayoutId = R.id.ll_ad_logo,              // Logo layout ID
    clickViewsIds = listOf(                      // Optional, specify clickable areas
        R.id.iv_ad_image,
        R.id.btn_ad_cta
    ),
    dislikeId = R.id.iv_ad_dislike               // Optional, dislike button
)

// Register view to enable interaction
adObject.registerViewForInteraction(
    activity,                                    // Activity context
    adView,                                      // Ad root view
    container,                                   // Container ViewGroup
    binder                                       // View binder
)

AdViewSize

Ad size config, data class. Unit is dp, only effective for banner and native template ads.

Fields

FieldTypeDefaultDescription
widthIntScreen width (dp)Ad width, unit dp
heightInt200Ad height, unit dp
kotlin
// Use default size (screen width × 200dp)
val defaultSize = AdViewSize()

// Custom size
val customSize = AdViewSize(
    width = 320,                                 // Width 320dp
    height = 50                                  // Height 50dp
)

Listener Interfaces

The SDK provides a set of listener interfaces, distinguished by ad type. All ad listeners inherit from BaseAdObjectListener.

Inheritance Hierarchy

BaseAdObjectListener
├── FeedAdObjectListener        (Banner / Native Feed)
├── SplashAdObjectListener      (Splash)
├── InterstitialAdObjectListener(Interstitial)
└── RewardAdObjectListener      (Rewarded Video)

BaseInitListener                (SDK init, standalone interface)

BaseAdObjectListener

Base interface for all ad object listeners.

Method SignatureDescription
onLoadSuccess(placementId: String)Ad loaded successfully, returns placement ID
onLoadError(error: UjuException, placementId: String)Ad load failed, returns error info and placement ID

Parameter Count Distinction

  • onLoadError has 2 parameters: error and placementId.
  • onAdError (in sub-interfaces) has 1 parameter: only error. Do not confuse the two.

FeedAdObjectListener

Banner ad and native feed ad listener, inherits BaseAdObjectListener.

Method SignatureDescription
onAdError(error: UjuException)Ad display error (1 parameter)
onAdShow()Ad displayed successfully
onAdClicked()Ad clicked
onAdClosed()Ad closed
onLpClosed()Landing page closed

SplashAdObjectListener

Splash ad listener, inherits BaseAdObjectListener.

Method SignatureDescription
onAdError(error: UjuException)Ad display error (1 parameter)
onAdShow()Ad displayed successfully
onAdClicked()Ad clicked
onAdClosed()Ad closed

InterstitialAdObjectListener

Interstitial ad listener, inherits BaseAdObjectListener.

Method SignatureDescription
onAdError(error: UjuException)Ad display error (1 parameter)
onAdShow()Ad displayed successfully
onAdPlayComplete()Ad playback complete
onAdClicked()Ad clicked
onLpClosed()Landing page closed
onAdClosed()Ad closed

RewardAdObjectListener

Rewarded video ad listener, inherits BaseAdObjectListener.

Method SignatureDescription
onAdShow()Ad displayed successfully
onAdError(error: UjuException)Ad display error (1 parameter)
onAdPlayComplete()Video playback complete
onAdClicked()Ad clicked
onAdSkippedVideo()User skipped video
onAdRewardArrived()Grant reward (no parameters, no RewardItem)
onAdClosed()Ad closed

onAdRewardArrived Has No Parameters

onAdRewardArrived() has no parameters; there is no RewardItem parameter. If you need to customize reward info, verify via Server-to-Server (S2S) callback on the server side.

BaseInitListener

SDK init listener, standalone interface, does not inherit BaseAdObjectListener.

Method SignatureDescription
onInitSuccess()SDK initialization successful
onInitFailed(error: UjuException)SDK initialization failed, returns error info
kotlin
// SDK init listener example
UjuAdSdk.start(object : BaseInitListener {
    override fun onInitSuccess() {
        // Init successful, can start loading ads
    }

    override fun onInitFailed(error: UjuException) {
        // Init failed, handle error
        Log.e("UjuAd", "Init failed: code=${error.code}, msg=${error.message}")
    }
})