目 录CONTENT

文章目录

Android Compose中展示Admob原生广告

Stars-one
2025-02-12 / 0 评论 / 0 点赞 / 5 阅读 / 3255 字

一个代码示例记录下

@Composable 
fun  AdmobBanner (modifier: Modifier = Modifier) { 
    AndroidView( 
        modifier = Modifier.fillMaxWidth(), 
        factory = { context -> 
            // 在下面一行指定广告视图。
             AdView(context).apply { 
                // 在下面一行指定广告尺寸
                //adSize = AdSize.BANNER 
                // 在下面一行指定广告单元 id 
                // 当前添加了一个测试广告单元 id。
                 setAdSize(AdSize.BANNER) 
                adUnitId = "ca-app-pub-3940256099942544/6300978111" 
                // 调用 load ad 来加载我们的广告。
                 loadAd(AdRequest.Builder().build()) 
            } 
        } 
    ) 
}

//简单一个示例
@Composable
fun AdContainer(modifier: Modifier = Modifier, adPlace: AdPlace = AdPlace.sunrepornav, withWait: Boolean = false) {
    val ispRev = LocalInspectionMode.current
    val scope = rememberCoroutineScope()

    //原生广告
    Box(modifier = modifier
        .fillMaxWidth()
        .let {
            if (ispRev) {
                it.background(Color.Red)
            } else {
                it
            }
        }
        .height(220.dp)
        .clip(RoundedCornerShape(16.dp))) { // Use AndroidView to embed WebView
        AndroidView(factory = { context ->
            FrameLayout(context).also {
                it.clipToOutline = true
            }
        }, update = { framelayout ->
            runCatching {
                if (withWait) {
                    scope.launch {
                        while (true) {
                            if (YAdController.hasLoadReportNav(adPlace)) { //AdjustUtils.adScen = adScene
                                YAdController.showNativeAd(adPlace, framelayout)
                                break
                            }
                            delay(500)
                        }
                    }
                }else{
                    YAdController.showNativeAd(adPlace, framelayout)
                }
            }
        }, modifier = Modifier.fillMaxSize()
        )
    }
}

参考

0

评论区