在長捲動或無限捲動清單 (例如新聞動態消息或社群動態) 中,為每個項目位置建立橫幅廣告,可能會導致記憶體用量過高和 UI 延遲。為提升效能,請使用橫幅廣告回收功能,維持小型的固定大小 BannerAd 執行個體快取,並在使用者捲動時重複使用螢幕外廣告。
本頁面說明如何調整廣告快取大小、檢查 BannerAd 執行個體是否在畫面外,以及將快取的廣告重新指派至清單位置。
下圖顯示使用者捲動畫面時,螢幕外的橫幅廣告如何返回快取,並在清單位置重複使用:
必要條件
繼續操作前,請先在可捲動內容中使用內嵌自動調整橫幅廣告。
追蹤指派的清單位置
使用者捲動畫面時,橫幅廣告回收機制會在記憶體中保留有限數量的 BannerAd 執行個體,並在清單位置之間移動這些執行個體。
如要瞭解要重複使用哪個廣告,請追蹤快取中每個廣告占用的清單位置。
在小工具中維護下列狀態:
BannerAd執行個體的固定大小快取。快取大小是指記憶體中可同時保留的廣告數量上限。- 廣告間隔,決定廣告在清單中顯示的頻率。
- 位置
Map類別,可將每個BannerAd例項與該例項佔用的清單位置建立關聯。回收廣告時,請更新這個Map類別中的項目,指向最新位置。 Map大小的類別,用於儲存每個已載入廣告的平台解析AdSize物件。廣告載入後,內嵌自動調整橫幅廣告的高度就會確定。
以下範例會追蹤快取中每個廣告的指派清單位置:
// Maximum number of banner ad instances kept in the cache.
static const int _cacheSize = 8;
// Spacing between banner ads. For example, index 0, 6, 12, and so on
// display ads.
static const int _adInterval = 6;
// The cache of allocated BannerAd instances.
final List<BannerAd> _banners = [];
// Maps each BannerAd instance to its currently assigned list item position.
final Map<BannerAd, int> _bannerPositions = {};
// Stores the platform-resolved size of each loaded banner ad.
final Map<BannerAd, AdSize> _bannerSizes = {};
選擇快取大小
快取大小應大於畫面上可同時顯示的廣告數量上限。如果快取小於該大小,系統通常仍會顯示選定回收的廣告,且應用程式會分配額外廣告,而非重複使用廣告。
如要選擇大小,請按照下列步驟操作:
- 將可視區域高度除以一個廣告間隔的高度,即可估算畫面上一次可容納多少廣告。
- 為快速捲動時仍會卸載的廣告新增空間。
- 如果發現系統選定回收的廣告仍顯示在畫面上,請增加快取大小。
本頁範例每六列顯示一則廣告,並使用八個快取。這個範例會預留空間,讓畫面上同時顯示幾則廣告。
檢查廣告是否顯示在畫面上
所有轉譯平台檢視畫面的 Google Mobile Ads Flutter Plugin 類別都會實作 AdWithView 類別,並提供 isMounted getter。將快取的廣告重新指派給清單位置前,請先檢查 isMounted getter,確認廣告已捲動至畫面外,可安全重複使用。
擷取及回收橫幅廣告
當清單要求在指定位置顯示橫幅廣告時,請執行下列操作:
- 重複使用已指派至該位置的廣告 (如果有的話)。
- 如果快取未滿,則請求廣告。
- 如果快取已滿,請選取快取廣告,並確認
isMountedgetter 為false值,再重新指派廣告。 - 從小工具樹狀結構中移除小工具時,請對快取中的每個廣告呼叫
dispose()方法。
以下範例會擷取並回收橫幅廣告:
BannerAd _getRecycledBannerAd(BuildContext context, int bannerPosition) {
// 1. If an ad is already mapped to this position, reuse it.
final BannerAd? existingBanner = _bannerPositions.entries
.firstWhereOrNull((entry) => entry.value == bannerPosition)
?.key;
if (existingBanner != null) {
return existingBanner;
}
// 2. If the cache is not full, allocate a new ad instance.
if (_banners.length < _cacheSize) {
final BannerAd newBanner = _createBannerAd(context);
_banners.add(newBanner);
_bannerPositions[newBanner] = bannerPosition;
return newBanner;
}
// 3. Select an existing ad from the cache using modulo arithmetic.
final BannerAd targetBanner = _banners[bannerPosition % _cacheSize];
// 4. Verify the ad is detached from the screen before recycling.
if (targetBanner.isMounted) {
// If still on screen during fast scrolls, allocate a temporary instance.
return _createBannerAd(context);
} else {
// Safe to reuse: reassign to the new position.
_bannerPositions[targetBanner] = bannerPosition;
return targetBanner;
}
}
如需完整範例,請參閱 Google Mobile Ads Flutter Plugin 範例。