googleads / googleads-mobile-android-native-templates

Apache License 2.0
116 stars 102 forks source link

Memory leak with com.google.android.gms:play-services-ads:20.0.0 #20

Open renezuidhof opened 3 years ago

renezuidhof commented 3 years ago

After upgrading to 20.0.0 I bumped into a memory leak after loading ads with the templates. Just sharing my findings for anyone else bumping into it.

I'm using https://github.com/googleads/googleads-mobile-android-native-templates/pull/17 since the latest master is not working with 20.0.0.

private var nativeAd: NativeAd? = null

private fun loadAd() {
        val adLoader = AdLoader.Builder(context, getAdId())
                .forNativeAd { nativeAd: NativeAd ->
                    this.nativeAd = nativeAd

                    val styles = NativeTemplateStyle.Builder().build()

                    adTemplate.setStyles(styles)
                    adTemplate.setNativeAd(nativeAd)
                }
                .build()

        adLoader.loadAd(AdRequest.Builder().build())
    }

Fix for the memory leak:

fun onDestroyView() {
        nativeAd?.destroy()
//        adTemplate.destroyNativeAd() // I'm not using this because it's not checking for null on the NativeAd

        adTemplate.nativeAdView.destroy() // This was the part I didn't expect to be needed
        adTemplate.removeAllViews()
    }