Xamarin.Forms Google 服务 AdMob

Xamarin.Forms Google Services AdMob

我正在尝试在我的 Xamarin.Forms 应用程序(目前为 Android 版本)中实施 AdMob。这是我到目前为止所做的:

  1. 在我的共享项目中创建了自定义控件 AdViewControl:
public class AdControlView : Xamarin.Forms.View
{
}
  1. 在我展示广告的页面中,我在 xaml 中添加了自定义控件:
xmlns:ads="clr-namespace:MyFeelingBuddyTwo.Views"
<ads:AdControlView BackgroundColor="Red"/> 
  1. 在Android项目(AndroidManifest.xml)中,在:

    
<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-myappid"/>
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

  1. 仍然在Android项目中,我创建了一个AdViewRenderer:

    
[assembly: ExportRenderer(typeof(MyFeelingBuddyTwo.Views.AdControlView), typeof(AdViewRenderer))]
namespace MyFeelingBuddyTwo.Droid
{
    class AdViewRenderer : ViewRenderer<Views.AdControlView, AdView>
    {
        string adUnitId = "myadunitid";
        AdSize adSize = AdSize.SmartBanner;
        AdView adView;

        AdView CreateAdView()
        {
            if (adView != null)
                return adView;

            adView = new AdView(Forms.Context);
            adView.AdSize = adSize;
            adView.AdUnitId = adUnitId;
            var arParams = new LinearLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
            adView.LayoutParameters = arParams;
            adView.LoadAd(new AdRequest.Builder().Build());

            return adView;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
        {
            base.OnElementChanged(e);
            if(Control == null)
            {
                CreateAdView();
                SetNativeControl(adView);
            }
        }
    }
}

  1. 在 MainActivity 中,在加载应用之前初始化 MobileAds:

    MobileAds.Initialize(ApplicationContext, "ca-app-pub-appid");
            

当我 运行 时,我得到红色背景但没有加载广告。有什么想法吗?

在 AdControlView class 中,我添加了:


    public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create("AdUnitId", typeof(string), typeof(AdControlView));
        
        public string AdUnitId
        {
            get { return (string)GetValue(AdUnitIdProperty); }
            set { SetValue(AdUnitIdProperty, value); }
        }

现在我可以在横幅占位符中看到“测试广告”。