本文介绍了如何以编程方式为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);

我得到:

所以第二个选择是以编程方式展示广告。

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.

尝试记录(mAdView.getAdSize()== null || mAdView.getAdUnitId()== null),然后调用loadAd确定其状态:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-09 09:44