如何以编程方式为 AdMob 指定 adUnitId? [英] How to specify adUnitId programmatically for AdMob?

查看:25
本文介绍了如何以编程方式为 AdMob 指定 adUnitId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式将 adUnitId 设置为来自新 Google Play 服务(旧 AdMob)的广告.

I'm trying to set adUnitId programmatically to ads from the new Google Play services (old AdMob).

我在 XML 中有这个(在 <include> 中使用):

I have this in XML (used in an <include>):

<com.google.android.gms.ads.AdView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"/>

这在 onCreate():

and this in onCreate():

AdView mAdview = (AdView)findViewById(R.id.adView);
    mAdview.setAdUnitId(((App)getApplication()).getAdmobKey());

    mAdview.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            findViewById(R.id.adView).setVisibility(View.VISIBLE);
        }
    });

    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    mAdview.loadAd(adRequest);

我得到:

必须在调用 loadAd 之前设置广告尺寸和广告单元 ID.

The ad size and ad unit ID must be set before loadAd is called.

因此,第二种选择是以编程方式制作广告.

So the second option was to make the ad programmatically.

新的 XML:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/adView"
    />

新代码:

AdView mAdview = new AdView(this);
...
((LinearLayout)findViewById(R.id.adView)).addView(mAdview);
mAdview.loadAd(adRequest);

但我得到了同样的错误.

But I get the same error.

我也尝试从 com.google.android.gms.ads.AdView 继承来制作自定义视图,但它是最终的.

I tried also to inherit from com.google.android.gms.ads.AdView to make a custom view, but it's final.

有什么建议吗?

推荐答案

方法 loadAd() 检查是否 (mAdView.getAdSize() == null || mAdView.getAdUnitId()== null) 当 loadAd 发生时.

The method loadAd() checks if (mAdView.getAdSize() == null || mAdView.getAdUnitId() == null) when loadAd happens.

在调用 loadAd 以确定其状态之前,尝试记录 (mAdView.getAdSize() == null || mAdView.getAdUnitId() == null) 的布尔输出:

Try logging the boolean output of (mAdView.getAdSize() == null || mAdView.getAdUnitId() == null) before calling loadAd to determine its state:

    mAdView = new AdView(this);
    mAdView.setAdSize(AdSize.BANNER);
    mAdView.setAdUnitId(AD_UNIT_ID);
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .build();
    if(mAdView.getAdSize() != null || mAdView.getAdUnitId() != null)
    mAdView.loadAd(adRequest);
   // else Log state of adsize/adunit
((LinearLayout)findViewById(R.id.adView)).addView(mAdview);

这篇关于如何以编程方式为 AdMob 指定 adUnitId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆