Search code examples
kotlinsdkdeprecatedbannerandroid-11

Adaptive Banner for Android 11 (SDK Version 30) - Kotlin - Deprecated


Good afternoon. This is my first consultation in the community. I am trying to implement an adaptive banner using the official documentation, but the example has deprecated terms and the help that Android Studio provides is confusing for me. I was looking for hours in the forum and I did not find an answer to help me. I would appreciate if you could help me implement an adaptive banner with Kotiln for SDK 30.

private lateinit var adView: AdView

private val adSize: AdSize
    get() {
        val display = windowManager.defaultDisplay
        val outMetrics = DisplayMetrics()
        display.getMetrics(outMetrics)

        val density = outMetrics.density

        var adWidthPixels = frameAnuncio.width.toFloat()
        if (adWidthPixels == 0f) {
            adWidthPixels = outMetrics.widthPixels.toFloat()
        }

        val adWidth = (adWidthPixels / density).toInt()
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
    }

Pic1

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_receta)
    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)

    MobileAds.initialize(this) { }

    adView = AdView(this)
    frameAnuncio.addView(adView)
    loadBanner()

}

private fun loadBanner() {
    adView.adUnitId = AD_UNIT_ID

    adView.adSize = adSize

    val adRequest = AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build()

    adView.loadAd(adRequest)
}

companion object {
    private val AD_UNIT_ID = "ca-app-pub-3940256099942544~3347511713"
}

Pic2

The Admob dependency is: Implementation 'com.google.android.gms: play-services-ads: 19.6.0'

Thank you


Solution

  • For the first part, you can use windowManager.currentDisplayMetrics to get access to window bounds. And resources.displayMetrics for access to the density.

    private val adSize: AdSize
        get() {
            val metrics = windowManager.currentWindowMetrics
    
            val density = resources.displayMetrics.density
    
            var adWidthPixels = frameAnuncio.width.toFloat()
            if (adWidthPixels == 0f) {
                adWidthPixels = metrics.bounds.width().toFloat()
            }
    
            val adWidth = (adWidthPixels / density).toInt()
            return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
        }
    

    The new way of adding a test device is explained in the documentation here.