Untitled

mail@pastecode.io avatar
unknown
kotlin
2 months ago
1.3 kB
3
Indexable
Never
fun loadNativeAd(context: Context, adUnitId: String, adLoadCallback: (NativeAd?) -> Unit) {
    CoroutineScope(Dispatchers.IO).launch {
        try {
            // Perform ad loading process on a background thread
            val adLoader = AdLoader.Builder(context, adUnitId)
                .forNativeAd { nativeAd ->
                    // Ad loaded successfully, update UI on the main thread
                    CoroutineScope(Dispatchers.Main).launch {
                        adLoadCallback(nativeAd)
                    }
                }
                .withAdListener(object : AdListener() {
                    override fun onAdFailedToLoad(adError: LoadAdError) {
                        // Ad loading failed, handle error and update UI on the main thread
                        CoroutineScope(Dispatchers.Main).launch {
                            adLoadCallback(null)
                        }
                    }
                })
                .build()

            adLoader.loadAd(AdRequest.Builder().build())
        } catch (e: Exception) {
            // Handle any exceptions
            CoroutineScope(Dispatchers.Main).launch {
                adLoadCallback(null)
            }
        }
    }
}
Leave a Comment