Skip to content

Instantly share code, notes, and snippets.

@shubhamvashisht
Created May 24, 2022 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubhamvashisht/5241d8ad338ede52cc58cf6b321cf8bd to your computer and use it in GitHub Desktop.
Save shubhamvashisht/5241d8ad338ede52cc58cf6b321cf8bd to your computer and use it in GitHub Desktop.
import android.content.Context
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.admanager.AdManagerAdRequest
import com.google.android.gms.ads.admanager.AdManagerAdView
import com.radio.pocketfm.app.ads.models.SizeModel
import com.radio.pocketfm.app.ads.listeners.AdStatusListener
import com.radio.pocketfm.app.helpers.*
class GamBannerAdServer(private val ctx: Context, val adUnitId: String, private val adSizes: List<AdSize?>, val statusListener: AdStatusListener?) :
BannerAdServer {
private lateinit var mAdManagerAdView: AdManagerAdView
private val adRequest: AdManagerAdRequest = AdManagerAdRequest.Builder().build()
init {
initAdAndSetListener(adUnitId)
}
override fun initAdAndSetListener(adUnitId: String) {
mAdManagerAdView = AdManagerAdView(ctx)
//AdView's AdUnitId and AdSizes must be initialized only once. hence this check to prevent Exception
if (mAdManagerAdView.adUnitId.isNull()) {
mAdManagerAdView.adUnitId = adUnitId
mAdManagerAdView.setAdSizes(*adSizes.toTypedArray())
}
mAdManagerAdView.adListener = object : AdListener() {
// Callback method Notifies that a banner ad successfully loaded
override fun onAdLoaded() {
super.onAdLoaded()
statusListener?.onAdLoaded(mAdManagerAdView, SizeModel(mAdManagerAdView.adSize?.width, mAdManagerAdView.adSize?.height))
}
// Callback method Notifies an error occurred while loading and ad
override fun onAdFailedToLoad(adError: LoadAdError) {
super.onAdFailedToLoad(adError)
statusListener?.onAdFailed()
}
// Callback method Notifies that the banner ad view closed the modal.
override fun onAdClosed() {
super.onAdClosed()
statusListener?.onAdClosed()
}
}
}
override fun loadBannerAd() {
mAdManagerAdView.loadAd(adRequest)
}
override fun pauseBannerAd() {
mAdManagerAdView.pause()
}
override fun resumeBannerAd() {
mAdManagerAdView.resume()
}
override fun destroyBannerAd() {
mAdManagerAdView.destroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment