如何以编程方式为 AdMob 指定 adUnitId?

编程入门 行业动态 更新时间:2024-10-28 20:26:22
本文介绍了如何以编程方式为 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="schemas.android/apk/res/android" xmlns:ads="schemas.android/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="schemas.android/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?

本文发布于:2023-07-27 05:19:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1220571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   AdMob   adUnitId

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!