You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Composable函数中获取当前Activity以调用插屏广告show方法

解决方案

你可以通过Compose提供的LocalContext上下文对象,安全转换得到当前关联的Activity实例,具体实现如下:

1. 实现Context转Activity的安全扩展函数(推荐)

避免直接强转出现类型转换异常,适配Context被多层ContextWrapper包装的场景:

fun Context.getActivity(): Activity? {
    var currentContext = this
    while (currentContext is ContextWrapper) {
        if (currentContext is Activity) {
            return currentContext
        }
        currentContext = currentContext.baseContext
    }
    return null
}

2. 在Composable的点击事件中调用广告方法

@Composable
fun InterstitialAdButton() {
    val context = LocalContext.current
    Button(
        onClick = {
            // 点击事件中获取当前Activity实例
            val currentActivity = context.getActivity()
            currentActivity?.let { activity ->
                if (mInterstitialAd != null) {
                    mInterstitialAd?.show(activity)
                } else {
                    Log.d("MainActivity", "The interstitial ad wasn't ready yet.")
                }
            }
        }
    ) {
        Text("展示插屏广告")
    }
}

注意事项

  • 不要在Composition阶段直接获取并长期持有Activity实例,仅在点击回调这类事件触发时临时获取使用,避免屏幕旋转等Configuration变更场景下持有旧Activity实例导致内存泄漏
  • 必须加非空判断,避免极端场景下Context无法转换为Activity导致崩溃

内容的提问来源于stack exchange,提问作者Raw Hasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:39:00