googleads-mobile-android-native-templates
googleads-mobile-android-native-templates copied to clipboard
Memory leak with com.google.android.gms:play-services-ads:20.0.0
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()
}