adstage
移动 SDK应用内事件

Android

AdStage 应用内事件对接指南(Android)

目录

  1. 概述
  2. 基本设置
  3. 类型安全的事件发送
  4. 标准事件目录
  5. 按事件类型的示例
  6. 最佳实践
  7. 疑难排查

概述

AdStage 应用内事件通过跟踪用户行为与应用事件,为营销分析和优化提供支持。

主要功能

  • 灵活的事件发送:从简单调用到详细的上下文
  • 自动收集上下文:自动包含设备信息、用户属性
  • 会话管理:自动跟踪与管理会话
  • Builder 模式:支持可读性高的 DSL 风格
  • 异步处理:基于 Coroutine 的 suspend 函数
  • 离线支持:网络重新连接时自动重新发送

基本设置

1. 添加 Gradle 依赖

settings.gradle.kts

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://repo.nbase.io/repository/nbase-releases") }
    }
}

build.gradle.kts (Module: app)

dependencies {
    implementation("io.nbase:nbase-adapter-adstage:3.0.9")
    
    // 必需依赖
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
    implementation("com.squareup.okhttp3:okhttp:4.11.0")
}

2. 初始化 SDK

import io.nbase.adapter.adstage.AdStage
 
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // 初始化 AdStage
        AdStage.initialize(
            context = this,
            apiKey = "your-api-key-here",
            serverUrl = "https://api.adstage.app" // 可选,可使用默认值
        )
        
        Log.d("AdStage", "✅ SDK 초기화 완료")
    }
}

3. AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
    <!-- 必需权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name">
        
        <!-- ... -->
        
    </application>
</manifest>

类型安全的事件发送

1. 最简单的方式

trackEvent 同时提供 suspend 函数与回调重载。 suspend 函数需在协程作用域内调用,在协程之外则使用回调版本。

import io.nbase.adapter.adstage.AdStage
import io.nbase.adapter.adstage.models.AdStageEvent
import io.nbase.adapter.adstage.models.SignUpMethod
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
 
CoroutineScope(Dispatchers.IO).launch {
    // 无参数的事件(suspend)
    AdStage.trackEvent(AdStageEvent.FirstOpen())
 
    // 登录事件(method 为字符串,使用 SignUpMethod enum 的 value)
    AdStage.trackEvent(
        AdStageEvent.Login(method = SignUpMethod.EMAIL.value)
    )
}
 
// 回调版本(不使用协程调用)
AdStage.trackEvent(AdStageEvent.Login(method = SignUpMethod.EMAIL.value)) { result ->
    when (result) {
        is TrackEventResult.Success -> Log.d("AdStage", "전송 성공")
        is TrackEventResult.Failure -> Log.e("AdStage", "전송 실패: ${result.error}")
    }
}

2. 购买事件(校验示例)

存在 value 时 currency 为必填。缺少时会在事件对象创建时点 抛出 IllegalArgumentException(运行时校验)。

// ✅ GOOD: value 与 currency 一起提供
AdStage.trackEvent(
    AdStageEvent.Purchase(
        value = 29.99,
        currency = "USD",
        transactionId = "TXN_123456"
    )
)
 
// ❌ BAD: 仅提供 value 时会抛出运行时异常(IllegalArgumentException)
AdStage.trackEvent(
    AdStageEvent.Purchase(
        value = 29.99  // ❌ 异常:有 value 时 currency 必填!
    )
)
 
// ✅ GOOD: 不带 currency,只提供 transactionId
AdStage.trackEvent(
    AdStageEvent.Purchase(
        transactionId = "TXN_123456"
    )
)

3. 商品浏览

// 带参数
AdStage.trackEvent(
    AdStageEvent.ProductDetailsView(
        itemId = "PROD_123",
        itemName = "Wireless Earbuds"
    )
)
 
// 不带参数
AdStage.trackEvent(AdStageEvent.ProductListView())

4. 自定义事件(event_name 自动提升)

除标准事件外,发送应用特有的事件时请使用 AdStageEvent.Custom。 若在参数中包含 event_name 键,该值会自动提升为实际的事件名称并保存到仪表板。

// 例:发送名为 'promotion_click' 的自定义事件
AdStage.trackEvent(
    AdStageEvent.Custom(
        params = mapOf(
            "event_name" to "promotion_click",
            "promotion_id" to "summer_sale_2025",
            "screen" to "home_banner"
        )
    )
)
// 在仪表板中会作为 "promotion_click" 事件收集
 
// 不带 event_name 的普通自定义事件
AdStage.trackEvent(
    AdStageEvent.Custom(
        params = mapOf(
            "action" to "button_click",
            "button_id" to "promo_banner",
            "screen" to "home",
            "timestamp" to System.currentTimeMillis()
        )
    )
)
// 在仪表板中会作为 "custom" 事件收集
 
// Click、View 同样支持自由参数
AdStage.trackEvent(
    AdStageEvent.Click(
        params = mapOf(
            "campaign_id" to "SUMMER2025",
            "ad_group" to "electronics"
        )
    )
)

标准事件目录

AdStage SDK 提供 46 个标准事件。

📌 广告跟踪(4 个)

// 1. 广告点击
AdStage.trackEvent(
    AdStageEvent.Click(
        params = mapOf("campaign_id" to "CAMP_123")
    )
)
 
// 2. 广告展示
AdStage.trackEvent(
    AdStageEvent.View(
        params = mapOf("impression_id" to "IMP_456")
    )
)
 
// 3. 应用安装
AdStage.trackEvent(AdStageEvent.Install())
 
// 4. 自定义事件(用 event_name 指定事件名称)
AdStage.trackEvent(
    AdStageEvent.Custom(
        params = mapOf(
            "event_name" to "promotion_click",
            "promotion_id" to "summer_sale_2025"
        )
    )
)

👤 用户生命周期(5 个)

SignUp 与 Login 的 method 是字符串(String?)参数。可以直接传入字符串, 也可以使用 SDK 提供的 SignUpMethod enum 的 .value。

// SDK 提供的 SignUpMethod enum(供参考)
enum class SignUpMethod(val value: String) {
    EMAIL("email"),
    GOOGLE("google"),
    APPLE("apple"),
    FACEBOOK("facebook"),
    KAKAO("kakao"),
    NAVER("naver")
}
 
// 1. 注册完成
AdStage.trackEvent(
    AdStageEvent.SignUp(method = SignUpMethod.GOOGLE.value)
)
 
// 2. 开始注册
AdStage.trackEvent(AdStageEvent.SignUpStart())
 
// 3. 登录(也可直接使用字符串:method = "email")
AdStage.trackEvent(
    AdStageEvent.Login(method = SignUpMethod.EMAIL.value)
)
 
// 4. 登出
AdStage.trackEvent(AdStageEvent.Logout())
 
// 5. 应用首次启动
AdStage.trackEvent(AdStageEvent.FirstOpen())

📄 内容浏览(6 个)

// 1. 首页画面
AdStage.trackEvent(AdStageEvent.HomeView())
 
// 2. 商品列表
AdStage.trackEvent(
    AdStageEvent.ProductListView(itemCategory = "electronics")
)
 
// 3. 搜索结果
AdStage.trackEvent(
    AdStageEvent.SearchResultView(searchTerm = "wireless headphones")
)
 
// 4. 商品详情
AdStage.trackEvent(
    AdStageEvent.ProductDetailsView(
        itemId = "PROD_123",
        itemName = "Wireless Earbuds"
    )
)
 
// 5. 页面浏览(Web)
AdStage.trackEvent(
    AdStageEvent.PageView(
        pageUrl = "https://example.com/products",
        pageTitle = "Products"
    )
)
 
// 6. 画面浏览(App)
AdStage.trackEvent(
    AdStageEvent.ScreenView(
        screenName = "product_detail",
        screenClass = "ProductDetailActivity"
    )
)

🛒 电子商务(7 个)

EcommerceItem 只有 itemId、itemName、price、quantity 这 4 个字段。

// 1. 加入购物车
AdStage.trackEvent(
    AdStageEvent.AddToCart(
        value = 99000.0,
        currency = "KRW",
        items = listOf(
            EcommerceItem(
                itemId = "PROD_123",
                itemName = "Wireless Earbuds",
                price = 99000.0,
                quantity = 1
            )
        )
    )
)
 
// 2. 从购物车移除
AdStage.trackEvent(
    AdStageEvent.RemoveFromCart(
        value = 50000.0,
        currency = "KRW"
    )
)
 
// 3. 加入心愿单
AdStage.trackEvent(
    AdStageEvent.AddToWishlist(
        itemId = "PROD_456",
        itemName = "Smart Watch"
    )
)
 
// 4. 输入支付信息
AdStage.trackEvent(
    AdStageEvent.AddPaymentInfo(paymentType = "credit_card")
)
 
// 5. 开始结算
AdStage.trackEvent(
    AdStageEvent.BeginCheckout(
        value = 150000.0,
        currency = "KRW"
    )
)
 
// 6. 购买完成 ⭐⭐⭐
AdStage.trackEvent(
    AdStageEvent.Purchase(
        value = 129000.0,
        currency = "KRW",
        transactionId = "ORDER_20250105_001",
        tax = 12900.0,
        shipping = 3000.0,
        coupon = "SUMMER2025",
        items = listOf(
            EcommerceItem(
                itemId = "PROD_123",
                itemName = "Wireless Earbuds",
                price = 126000.0,
                quantity = 1
            )
        )
    )
)
 
// 7. 退款
AdStage.trackEvent(
    AdStageEvent.Refund(
        transactionId = "ORDER_20250105_001",
        value = 129000.0,
        currency = "KRW"
    )
)

🎮 进度与成就(4 个)

// 1. 开始新手教程
AdStage.trackEvent(
    AdStageEvent.TutorialBegin(
        params = mapOf("tutorial_id" to "intro")
    )
)
 
// 2. 完成新手教程
AdStage.trackEvent(
    AdStageEvent.TutorialComplete(
        params = mapOf("duration_seconds" to 120)
    )
)
 
// 3. 升级
AdStage.trackEvent(
    AdStageEvent.LevelUp(
        level = 25,
        character = "warrior"
    )
)
 
// 4. 达成成就
AdStage.trackEvent(
    AdStageEvent.Achievement(achievementId = "first_win")
)

💬 互动(7 个)

// 1. 搜索
AdStage.trackEvent(
    AdStageEvent.Search(searchTerm = "gaming laptop")
)
 
// 2. 选择内容
AdStage.trackEvent(
    AdStageEvent.SelectContent(
        contentType = "product",
        contentId = "PROD_789"
    )
)
 
// 3. 分享
AdStage.trackEvent(
    AdStageEvent.Share(
        contentType = "product",
        method = "kakao"
    )
)
 
// 4. 点赞
AdStage.trackEvent(
    AdStageEvent.Like(
        contentType = "product",
        contentId = "PROD_789"
    )
)
 
// 5. 评分
AdStage.trackEvent(
    AdStageEvent.Rate(
        contentType = "product",
        contentId = "PROD_789",
        score = 4.5
    )
)
 
// 6. 登记日程
AdStage.trackEvent(
    AdStageEvent.Schedule(
        params = mapOf("event_type" to "appointment")
    )
)
 
// 7. 使用点数
AdStage.trackEvent(
    AdStageEvent.SpendCredits(
        value = 10.0,
        itemName = "premium_feature"
    )
)

📢 应用内广告(2 个)

// 1. 应用内广告展示
AdStage.trackEvent(
    AdStageEvent.AdImpression(
        adPlatform = "admob",
        adFormat = "rewarded_video",
        adUnitName = "main_reward"
    )
)
 
// 2. 应用内广告点击
AdStage.trackEvent(
    AdStageEvent.AdClick(
        adPlatform = "admob",
        adFormat = "banner",
        adUnitName = "home_bottom"
    )
)

🎮 游戏专用(4 个)

// 1. 游戏进行
AdStage.trackEvent(
    AdStageEvent.GamePlay(
        level = 10,
        levelName = "Dragon's Lair",
        character = "mage",
        contentType = "dungeon"
    )
)
 
// 2. 获得奖励
AdStage.trackEvent(
    AdStageEvent.AcquireBonus(
        contentType = "reward",
        itemId = "ITEM_123",
        itemName = "Gold Chest",
        quantity = 1
    )
)
 
// 3. 选择游戏服务器
AdStage.trackEvent(
    AdStageEvent.SelectGameServer(
        contentId = "SERVER_01",
        contentType = "pvp",
        itemName = "Asia Server"
    )
)
 
// 4. 补丁完成
AdStage.trackEvent(
    AdStageEvent.CompletePatch(
        contentId = "PATCH_2.1.0",
        contentType = "update"
    )
)

📅 订阅与试用(3 个)

// 1. 开始免费试用
AdStage.trackEvent(
    AdStageEvent.StartTrial(
        value = 9900.0,
        currency = "KRW",
        trialDays = 14
    )
)
 
// 2. 开始订阅
AdStage.trackEvent(
    AdStageEvent.Subscribe(
        value = 9900.0,
        currency = "KRW",
        subscriptionId = "premium_monthly"
    )
)
 
// 3. 取消订阅
AdStage.trackEvent(
    AdStageEvent.Unsubscribe(subscriptionId = "premium_monthly")
)

💰 金融专用(4 个)

// 1. 买入股票
AdStage.trackEvent(
    AdStageEvent.BuyStock(
        itemId = "005930",
        itemName = "삼성전자",
        quantity = 10,
        price = 70000.0,
        value = 700000.0,
        currency = "KRW"
    )
)
 
// 2. 卖出股票
AdStage.trackEvent(
    AdStageEvent.SellStock(
        itemId = "005930",
        itemName = "삼성전자",
        quantity = 5,
        price = 72000.0,
        value = 360000.0,
        currency = "KRW"
    )
)
 
// 3. 开户完成
AdStage.trackEvent(
    AdStageEvent.CompleteOpenAccount(
        contentType = "증권계좌",
        contentId = "ACC_123",
        method = "mobile"
    )
)
 
// 4. 申请信用卡
AdStage.trackEvent(
    AdStageEvent.ApplyCard(
        contentType = "신용카드",
        itemName = "프리미엄 카드",
        itemId = "CARD_001"
    )
)

按事件类型的示例

1. 应用生命周期

class MyApplication : Application() {
    
    override fun onCreate() {
        super.onCreate()
        
        // 初始化 SDK
        AdStage.initialize(this, apiKey, serverUrl)
        
        // 首次启动事件由 SDK 自动发送
        Log.d("App", "✅ 앱 시작")
    }
}

2. 用户认证

class AuthManager {
    
    // 注册(method 为字符串参数)
    fun onSignUpComplete(method: String) {
        AdStage.trackEvent(
            AdStageEvent.SignUp(method = method)
        )
        
        Log.d("Auth", "✅ 회원가입 완료: $method")
    }
    
    // 登录
    fun onLoginSuccess(userId: String, method: String) {
        AdStage.trackEvent(
            AdStageEvent.Login(method = method)
        )
        
        Log.d("Auth", "✅ 로그인: $userId")
    }
    
    // 登出
    fun onLogout() {
        AdStage.trackEvent(AdStageEvent.Logout())
        Log.d("Auth", "🚪 로그아웃")
    }
}

3. 画面跟踪(BaseActivity 模式)

abstract class BaseActivity : AppCompatActivity() {
    
    override fun onResume() {
        super.onResume()
        trackScreenView()
    }
    
    abstract fun getScreenName(): String
    
    private fun trackScreenView() {
        AdStage.trackEvent(
            AdStageEvent.ScreenView(
                screenName = getScreenName(),
                screenClass = this::class.java.simpleName
            )
        )
        
        Log.d("Screen", "📺 ${getScreenName()}")
    }
}
 
// 使用示例
class HomeActivity : BaseActivity() {
    override fun getScreenName() = "home"
}
 
class ProductDetailActivity : BaseActivity() {
    override fun getScreenName() = "product_detail"
    
    private fun loadProduct(productId: String) {
        // 加载商品数据...
        
        // 商品详情浏览事件
        AdStage.trackEvent(
            AdStageEvent.ProductDetailsView(
                itemId = productId,
                itemName = product.name
            )
        )
    }
}

4. 电子商务完整流程

class EcommerceManager {
    
    // 1. 浏览商品列表
    fun trackProductList(category: String) {
        AdStage.trackEvent(
            AdStageEvent.ProductListView(itemCategory = category)
        )
    }
    
    // 2. 搜索
    fun trackSearch(query: String) {
        AdStage.trackEvent(
            AdStageEvent.Search(searchTerm = query)
        )
    }
    
    // 3. 浏览搜索结果
    fun trackSearchResults(query: String) {
        AdStage.trackEvent(
            AdStageEvent.SearchResultView(searchTerm = query)
        )
    }
    
    // 4. 浏览商品详情
    fun trackProductView(product: Product) {
        AdStage.trackEvent(
            AdStageEvent.ProductDetailsView(
                itemId = product.id,
                itemName = product.name
            )
        )
    }
    
    // 5. 加入购物车
    fun trackAddToCart(product: Product, quantity: Int) {
        val item = EcommerceItem(
            itemId = product.id,
            itemName = product.name,
            price = product.price,
            quantity = quantity
        )
        
        AdStage.trackEvent(
            AdStageEvent.AddToCart(
                value = product.price * quantity,
                currency = "KRW",
                items = listOf(item)
            )
        )
    }
    
    // 6. 加入心愿单
    fun trackAddToWishlist(product: Product) {
        AdStage.trackEvent(
            AdStageEvent.AddToWishlist(
                itemId = product.id,
                itemName = product.name
            )
        )
    }
    
    // 7. 开始结算
    fun trackBeginCheckout(cart: Cart) {
        val items = cart.items.map { cartItem ->
            EcommerceItem(
                itemId = cartItem.product.id,
                itemName = cartItem.product.name,
                price = cartItem.product.price,
                quantity = cartItem.quantity
            )
        }
        
        AdStage.trackEvent(
            AdStageEvent.BeginCheckout(
                value = cart.totalAmount,
                currency = "KRW",
                items = items
            )
        )
    }
    
    // 8. 输入支付信息
    fun trackAddPaymentInfo(paymentMethod: String) {
        AdStage.trackEvent(
            AdStageEvent.AddPaymentInfo(paymentType = paymentMethod)
        )
    }
    
    // 9. 购买完成 ⭐⭐⭐
    fun trackPurchase(order: Order) {
        val items = order.items.map { orderItem ->
            EcommerceItem(
                itemId = orderItem.product.id,
                itemName = orderItem.product.name,
                price = orderItem.product.price,
                quantity = orderItem.quantity
            )
        }
        
        AdStage.trackEvent(
            AdStageEvent.Purchase(
                value = order.totalAmount,
                currency = "KRW",
                transactionId = order.id,
                tax = order.tax,
                shipping = order.shippingFee,
                coupon = order.couponCode,
                items = items
            )
        )
        
        Log.d("Ecommerce", "✅ 구매 완료: ${order.id}, ${order.totalAmount}원")
    }
    
    // 10. 退款
    fun trackRefund(order: Order) {
        AdStage.trackEvent(
            AdStageEvent.Refund(
                transactionId = order.id,
                value = order.totalAmount,
                currency = "KRW"
            )
        )
    }
    
    // 11. 分享
    fun trackShare(product: Product, method: String) {
        AdStage.trackEvent(
            AdStageEvent.Share(
                contentType = "product",
                method = method
            )
        )
    }
}

5. 游戏事件

class GameEventManager {
    
    // 新手教程
    fun trackTutorialBegin(tutorialId: String) {
        AdStage.trackEvent(
            AdStageEvent.TutorialBegin(
                params = mapOf("tutorial_id" to tutorialId)
            )
        )
    }
    
    fun trackTutorialComplete(tutorialId: String, duration: Long) {
        AdStage.trackEvent(
            AdStageEvent.TutorialComplete(
                params = mapOf(
                    "tutorial_id" to tutorialId,
                    "duration_seconds" to duration / 1000
                )
            )
        )
    }
    
    // 等级
    fun trackLevelUp(level: Int, character: String) {
        AdStage.trackEvent(
            AdStageEvent.LevelUp(
                level = level,
                character = character
            )
        )
    }
    
    // 成就
    fun trackAchievement(achievementId: String) {
        AdStage.trackEvent(
            AdStageEvent.Achievement(achievementId = achievementId)
        )
    }
    
    // 游戏进行
    fun trackGameStart(level: Int, levelName: String, character: String) {
        AdStage.trackEvent(
            AdStageEvent.GamePlay(
                level = level,
                levelName = levelName,
                character = character,
                contentType = "pvp"
            )
        )
    }
    
    // 获得奖励
    fun trackBonusAcquired(itemId: String, itemName: String, quantity: Int) {
        AdStage.trackEvent(
            AdStageEvent.AcquireBonus(
                contentType = "reward",
                itemId = itemId,
                itemName = itemName,
                quantity = quantity
            )
        )
    }
    
    // 使用点数(游戏货币)
    fun trackSpendCredits(amount: Double, itemName: String) {
        AdStage.trackEvent(
            AdStageEvent.SpendCredits(
                value = amount,
                itemName = itemName
            )
        )
    }
}

最佳实践

1. 活用 Extension 函数

// ActivityExtensions.kt
fun Activity.trackScreen() {
    val screenName = this::class.java.simpleName
        .removeSuffix("Activity")
        .lowercase()
    
    AdStage.trackEvent(
        AdStageEvent.ScreenView(
            screenName = screenName,
            screenClass = this::class.java.simpleName
        )
    )
}
 
// 使用
class ProfileActivity : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        trackScreen()  // ✅ 简单!
    }
}

2. 在 ViewModel 中跟踪事件

class ProductViewModel : ViewModel() {
    
    private val _productState = MutableLiveData<Product>()
    val productState: LiveData<Product> = _productState
    
    fun loadProduct(productId: String) {
        viewModelScope.launch {
            try {
                val product = repository.getProduct(productId)
                _productState.value = product
                
                // 商品浏览事件
                AdStage.trackEvent(
                    AdStageEvent.ProductDetailsView(
                        itemId = product.id,
                        itemName = product.name
                    )
                )
                
            } catch (e: Exception) {
                Log.e("ProductVM", "Failed to load product", e)
            }
        }
    }
    
    fun addToCart(product: Product, quantity: Int) {
        viewModelScope.launch {
            try {
                repository.addToCart(product, quantity)
                
                val item = EcommerceItem(
                    itemId = product.id,
                    itemName = product.name,
                    price = product.price,
                    quantity = quantity
                )
                
                AdStage.trackEvent(
                    AdStageEvent.AddToCart(
                        value = product.price * quantity,
                        currency = "KRW",
                        items = listOf(item)
                    )
                )
                
            } catch (e: Exception) {
                Log.e("ProductVM", "Failed to add to cart", e)
            }
        }
    }
}

3. 在 Compose UI 中使用

@Composable
fun ProductDetailScreen(
    productId: String,
    viewModel: ProductViewModel = hiltViewModel()
) {
    val product by viewModel.productState.collectAsState()
    
    // 进入画面时的事件
    LaunchedEffect(productId) {
        viewModel.loadProduct(productId)
        
        AdStage.trackEvent(
            AdStageEvent.ScreenView(
                screenName = "product_detail",
                screenClass = "ProductDetailScreen"
            )
        )
    }
    
    Column {
        // UI...
        
        Button(
            onClick = {
                viewModel.addToCart(product, 1)
                
                AdStage.trackEvent(
                    AdStageEvent.Custom(
                        params = mapOf(
                            "action" to "add_to_cart_button",
                            "product_id" to product.id
                        )
                    )
                )
            }
        ) {
            Text("장바구니에 추가")
        }
    }
}

4. 事件包装类

object AnalyticsManager {
    
    private const val TAG = "Analytics"
    
    fun trackScreen(screenName: String, screenClass: String? = null) {
        AdStage.trackEvent(
            AdStageEvent.ScreenView(
                screenName = screenName,
                screenClass = screenClass
            )
        )
        Log.d(TAG, "📺 Screen: $screenName")
    }
    
    fun trackPurchase(order: Order) {
        val items = order.items.map {
            EcommerceItem(
                itemId = it.product.id,
                itemName = it.product.name,
                price = it.product.price,
                quantity = it.quantity
            )
        }
        
        AdStage.trackEvent(
            AdStageEvent.Purchase(
                value = order.totalAmount,
                currency = "KRW",
                transactionId = order.id,
                items = items
            )
        )
        
        Log.d(TAG, "💰 Purchase: ${order.id}")
    }
    
    fun trackError(error: Throwable, context: String) {
        AdStage.trackEvent(
            AdStageEvent.Custom(
                params = mapOf(
                    "event_type" to "error",
                    "error_message" to (error.message ?: "unknown"),
                    "context" to context
                )
            )
        )
        Log.e(TAG, "❌ Error: $context", error)
    }
}

5. 性能优化:Throttling

class ThrottledEventTracker {
    private val lastTrackTimes = mutableMapOf<String, Long>()
    private val throttleInterval = 2000L  // 2 秒
    
    fun trackEvent(event: AdStageEvent) {
        val eventKey = event.eventName
        val now = System.currentTimeMillis()
        val lastTime = lastTrackTimes[eventKey] ?: 0L
        
        if (now - lastTime >= throttleInterval) {
            AdStage.trackEvent(event)
            lastTrackTimes[eventKey] = now
        } else {
            Log.d("AdStage", "⏱️ Throttled: $eventKey")
        }
    }
}
 
// 使用(滚动事件等)
val throttledTracker = ThrottledEventTracker()
 
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        throttledTracker.trackEvent(
            AdStageEvent.Custom(
                params = mapOf(
                    "action" to "scroll",
                    "delta_y" to dy
                )
            )
        )
    }
})

转换示例(基于字符串 → 类型安全 API)

当前 SDK 仅支持 AdStageEvent 类型安全事件。下面是将基于字符串的 事件名称转换为类型安全事件的示例(箭头右侧为实际使用形式)。

// 1. 基本事件
"first_open"
→ AdStage.trackEvent(AdStageEvent.FirstOpen())
 
// 2. 登录(method 为字符串参数)
"login", method = "email"
→ AdStage.trackEvent(AdStageEvent.Login(method = "email"))
 
// 3. 画面浏览
"screen_view", screen_name = "home"
→ AdStage.trackEvent(AdStageEvent.ScreenView(screenName = "home"))
 
// 4. 自定义
"custom", action = "click"
→ AdStage.trackEvent(AdStageEvent.Custom(params = mapOf("action" to "click")))

疑难排查

1. 运行时异常:“存在 value 时 currency 为必填”

问题:

// ❌ IllegalArgumentException(事件对象创建时点)
AdStage.trackEvent(
    AdStageEvent.Purchase(value = 9900.0)
)

解决:

// ✅ 添加 currency(ISO 4217,3 位)
AdStage.trackEvent(
    AdStageEvent.Purchase(
        value = 9900.0,
        currency = "KRW"
    )
)

2. IDE 自动补全不生效

解决:

  1. Gradle Sync: File → Sync Project with Gradle Files
  2. Invalidate Caches: File → Invalidate Caches / Restart...
  3. 确认 Import:
import io.nbase.adapter.adstage.models.AdStageEvent.*
 
// 现在自动补全即可生效
AdStage.trackEvent(Purchase(...))

3. ProGuard/R8 混淆问题

# proguard-rules.pro

# 保留 AdStage 事件模型
-keep class io.nbase.adapter.adstage.models.** { *; }
-keepclassmembers class io.nbase.adapter.adstage.models.** { *; }

# AdStageEvent sealed class
-keep class io.nbase.adapter.adstage.models.AdStageEvent { *; }
-keep class io.nbase.adapter.adstage.models.AdStageEvent$* { *; }

# Kotlin Metadata
-keep class kotlin.Metadata { *; }

4. 货币代码校验错误

// ❌ 2 位代码
AdStageEvent.Purchase(value = 100.0, currency = "KR")
// IllegalArgumentException: "currency 必须是 ISO 4217 的 3 位代码(例如:USD、KRW)"
 
// ✅ 3 位 ISO 4217 代码
AdStageEvent.Purchase(value = 100.0, currency = "KRW")  // 韩元
AdStageEvent.Purchase(value = 100.0, currency = "USD")  // 美元
AdStageEvent.Purchase(value = 100.0, currency = "JPY")  // 日元

主要货币代码:

国家货币代码
韩国韩元KRW
美国美元USD
日本日元JPY
欧盟欧元EUR
英国英镑GBP

5. 查看调试日志

SDK 会以 AdStage / AdapterAdStage 标签输出日志。使用下面的筛选条件,可在 Logcat 中 确认事件发送流程。

Logcat 筛选条件:

# Android Studio
tag:AdStage OR tag:AdapterAdStage
 
# adb
adb logcat | grep -i adstage

参考资料

标准参考


FAQ

Q: 自定义事件该如何发送?
A: 使用 AdStageEvent.Custom(params = mapOf(...))

Q: 可以不带 value 只使用 currency 吗?
A: 不可以,使用 value 时 currency 为必填。

Q: 离线状态下也能工作吗?
A: 可以,SDK 会自动把事件存入队列,网络恢复时再发送。


支持

联系方式:


© 2025 NBase. All rights reserved.

目录