Background
I'm trying to implement support for native ads from Admob.
The problem
I've noticed this requirement:
Ensure that all UnifiedNativeAd references are destroyed in your activity's onDestroy() method.
In your onUnifiedNativeAdLoaded callback, make sure to destroy any existing native ads that will be dereferenced.
However, I want to preload ads even before reaching the Activity, and if possible to re-use an ad when the Activity is recreated via configuration change (or at least on orientation change). Maybe even re-use the ad in multiple places, to reduce time of re-loading.
What I've found
I couldn't find explanation about this, except that it's ok to preload:
https://developers.google.com/admob/android/native/start?hl=en-US#when_to_request_ads
It also says that we shouldn't use ads that were preloaded and weren't used for an hour:
Any ad objects that have been held for longer than an hour without being displayed should be discarded and replaced with new ads from a new request.
As for the requirement to destroy the ad when there are no references to it, I've put a wrapper of the ad into a cached reference, and if I don't need it anymore I remove it from the cache. The wrapper should get rid of the ad using finalize
, as such:
class UnifiedNativeAdWrapper(private val ad: UnifiedNativeAd) {
@UiThread
fun getAd(): UnifiedNativeAd? {
if (isDestroyed)
return null
return ad
}
@Suppress("MemberVisibilityCanBePrivate")
var isDestroyed = false
private set
@Suppress("unused", "ProtectedInFinal")
protected fun finalize() = destroy()
@UiThread
fun destroy() {
if (isDestroyed)
return
isDestroyed = true
ad.destroy()
}
}
The questions
Is it ok to avoid destroying so quickly, on every time the Activity is destroyed? Maybe to destroy the ad only when it doesn't change configuration?
Is it ok to have the wrapper I've made?
Since it says that I should also avoid using ads that weren't used for an hour since being loaded, what happens to UnifiedNativeAdView that used an UnifiedNativeAd, once I call
destroy
on the UnifiedNativeAd ? Is it ok to calldestroy
on the old one that was used, while loading a new one? I want to avoid removal of the View while loading a new one...Since it says there could be multiple references to the ad, can the same instance of UnifiedNativeAd be used in multiple places (different Activities) ?