Recyclerview适配器中的Admob原生广告destroy方法

问题描述

我正在使用admob原生广告模板。 Admob建议在本机广告上使用destroy()方法,以避免内存泄漏。建议在活动的onDestroy()方法调用方法

if (isDestroyed()) {
            ad.destroy();
            return;
        } 

我正在使用recyclerview,并且已将mainactivity上的广告初始化为

MobileAds.initialize(MainActivity.this,"ca-app-pub-3940256099942544~3347511713");

但是我已经使用get itemviewtype将其余的广告代码放置在recyclerview适配器中

@Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder,final int position) {

if (getItemViewType(position) == AD_TYPE){

            final AdLoader adLoader = new AdLoader.Builder(context,"ca-app-pub-3940256099942544/2247696110")
                    .forUnifiednativeAd(new UnifiednativeAd.OnUnifiednativeAdLoadedListener() {
                        @Override
                        public void onUnifiednativeAdLoaded(UnifiednativeAd unifiednativeAd) {
                            // Show the ad.
                            NativeTemplateStyle styles = new
                                    NativeTemplateStyle.Builder().build();

                            TemplateView template = ((adViewHolder) holder).Adtemplate;
                            template.setStyles(styles);
                            template.setNativeAd(unifiednativeAd);

                        }
                    })
                    .withAdListener(new AdListener() {
                        @Override
                        public void onAdFailedToLoad(int errorCode) {
                            // Handle the failure by logging,altering the UI,and so on.
                        }
                    })
                    .withNativeAdOptions(new NativeAdOptions.Builder()
                            // Methods in the NativeAdOptions.Builder class can be
                            // used here to specify individual options settings.
                            .build())
                    .build();
            adLoader.loadAd(new AdRequest.Builder().build());


        }

在这种情况下,我应该在哪里执行ad.destroy()方法?另外,我是否需要对原生广告模板执行其他任何方法?任何帮助将不胜感激。

解决方法

使用您自己的功能来销毁广告,并从活动onDestroy调用它

在您的适配器中执行以下功能

public void destroyAds() {
    ad.destroy();
}

然后从活动onDestroy()调用该函数

@Override
public void onDestroy() {
    adapter.destroyAds();
}