如何避免在配置更改和启动 Activity 时重新加载 Admob 广告?

How to avoid re-loading of Admob ads upon configuration change and starting an Activity?

使用横幅示例 here,我注意到如果我改变方向,广告就会消失,然后重新加载(需要时间),所以有一段时间没有显示任何内容,每次我改变方向。

我知道可以通过清单为 activity 设置 configChanges(它确实有效),但通常不推荐这样做。它有多个缺陷:

  1. 例如,在我的例子中,改变方向让工具栏保持在相同的高度,这是错误的,因为它在横向和纵向上应该不同。
  2. 转到另一个 Activity Admob 视图仍会重新加载,即使它之前已加载。
  3. 从纵向变为横向时,反之亦然,广告无法很好地适应新方向。

还有什么可以避免在每次配置更改时重新加载广告?

我希望 Admob 加载一次广告(对于新广告,其余的在后台加载),然后显示它们,并避免在我改变方向时重新加载。每次我到达它时,只显示最适合当前配置的配置(例如方向)。

转到具有 Admob 广告的新 Activity 也是如此。如果之前加载过,无需重新加载。


编辑:我悬赏了这个,因为 Google/Firebase 支持人员通过电子邮件告诉我实际上可以缓存广告:

The Ads SDK won't cache ads for you, however you can implement an 'AdManager' style class, most likely a singleton or an instance attached to your application instance, which can manage caching for you.

As you recognize it's an Android pattern to destroy and recreate activities on orientation, instance state is usually saved and restored via a bundle, but this is not applicable to views.

If you wish to optimize the reload time of the banner view in this scenario, I would recommend making your ad request via an AdManager class, and the AdManager can then apply some logic to cache ads such as your banner view for a certain amount of time, and return the previous banner if it is still valid for the new request (which you would make on orientation change).

并且:

This idea of caching ads is not implemented by the SDK, as it is difficult to determine the best caching logic to apply in all cases, thus it is left to the developer to implement caching that suits their use case, if desired.

Possibly having a banner ad decoupled from the 'AdView' class would make for more appropriate cacheable objects, however this is not currently the case.

Therefore as it is, yes we suggest that in order to prefetch / cache a banner ad, you need to store the 'AdView'. Instead of using an AdManager however, another supported and indeed recommended approach would be to use a ViewModel, see https://developer.android.com/guide/topics/resources/runtime-changes#RetainingAnObject and https://developer.android.com/topic/libraries/architecture/viewmodel. These are designed for exactly this kind of use case.

如果真的可以的话,我想知道具体怎么做。请,无论谁成功了,请在代码中展示可以做什么。

我认为使用智能横幅是个不错的选择,因为它们适用于任何方向 要使用智能横幅,请为广告尺寸指定常量 SMART_BANNER

AdView adView = new AdView(this);

adView.setAdSize(AdSize.SMART_BANNER);

还要检查这个: https://firebase.google.com/docs/admob/android/banner#smart_banners

我没有看到如何缓存普通广告的明确方法。单例和视图模型都无济于事,我们无法 cache/retain 视图本身,也没有 public 广告对象可保留。

但是 AdLoader 使用它可以加载原生广告,并保留加载的 UnifiedNativeAd 对象。然后就可以用来设置广告可见了。

其他广告 SDK 提供了预取广告的方法。

P.S。不知道为什么堆栈在 "android viewmodel" 查询

的搜索结果中带来了这个

似乎拥有原生广告是最好的选择,而不是 configChanges 。例如,可以将纯数据保存在 Fragment/Activity 的 ViewModel 中,以便您再次使用它。

遗憾的是,这是一个您必须自己实施的解决方案,不仅包括它的外观,还包括加载过程本身,包括何时自行重新加载。

根据个人需要,需要阅读和实施的内容很多,因此最好从 :

开始

https://developers.google.com/admob/android/native/start

不确定在收入方面是否与横幅广告大致相同。