在MAUI中通过Xamarin.GooglePlayServices.Ads.Lite集成AdMob遇问题求助
MAUI 中实现 AdMob 原生广告的解决方案
针对你遇到的三个问题,直接给出解决方案及完整实现示例:
问题1:Microsoft.Maui.Controls.Compatibility.Forms.Init() 重载找不到
直接移除该调用即可。MAUI 框架已经内置了 Forms 兼容层的初始化逻辑,不需要手动调用这个方法,Xamarin 时代的初始化步骤在 MAUI 中已被整合到启动流程里。
问题2:builder.SetTestDeviceIds 填入内容说明
这里必须填入测试设备ID,而非广告单元ID。测试设备ID用于标识你的测试设备,让 AdMob 返回测试广告,避免触发真实广告的计费规则及违反平台政策。
获取测试设备ID的方式:运行应用后,查看 Android Logcat 日志,找到类似以下内容的行,复制引号内的字符串即可:
Use AdRequest.Builder.addTestDevice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") to get test ads on this device.
问题3:MAUI 中无 LoadApplication(new App()); 方法
MAUI 不需要手动调用这个方法。应用的加载逻辑已移至 MauiProgram.cs 的 CreateMauiApp 方法,框架会自动通过该方法返回的 MauiApp 实例完成应用启动,直接移除该调用即可。
完整原生广告实现示例
1. Android 项目初始化配置(Platforms/Android/MainApplication.cs)
using Android.App; using Android.Runtime; using GoogleMobileAds; using System.Collections.Generic; namespace YourAppName.Droid; [Application] public class MainApplication : MauiApplication { public MainApplication(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); public override void OnCreate() { base.OnCreate(); // 初始化 AdMob MobileAds.Initialize(ApplicationContext, _ => { }); // 设置测试设备ID,替换为你的设备ID var config = new RequestConfiguration.Builder() .SetTestDeviceIds(new List<string> { "你的测试设备ID" }) .Build(); MobileAds.SetRequestConfiguration(config); } }
2. 共享项目创建原生广告控件
using Microsoft.Maui.Controls; namespace YourAppName; public class NativeAdView : View { public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(nameof(AdUnitId), typeof(string), typeof(NativeAdView), string.Empty); public string AdUnitId { get => (string)GetValue(AdUnitIdProperty); set => SetValue(AdUnitIdProperty, value); } }
3. Android 项目实现原生广告 Handler(替代Xamarin渲染器)
先在 Android 项目的 Resources/layout 下创建 native_ad_layout.xml 布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp" android:background="#f5f5f5"> <TextView android:id="@+id/ad_attribution" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp" android:textColor="#888"/> <ImageView android:id="@+id/ad_icon" android:layout_width="48dp" android:layout_height="48dp" android:layout_marginTop="8dp"/> <TextView android:id="@+id/ad_headline" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:textStyle="bold" android:layout_marginTop="8dp"/> <TextView android:id="@+id/ad_body" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="#444" android:layout_marginTop="4dp"/> <Button android:id="@+id/ad_call_to_action" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="#2196F3" android:textColor="#ffffff"/> </LinearLayout>
然后创建 Handler 类:
using Android.Content; using Android.Widget; using GoogleMobileAds; using GoogleMobileAds.Api; using Microsoft.Maui.Handlers; using YourAppName; using YourAppName.Droid; namespace YourAppName.Droid; public class NativeAdViewHandler : ViewHandler<NativeAdView, FrameLayout> { private NativeAdLoader _adLoader; private NativeAd _nativeAd; private FrameLayout _adContainer; protected override FrameLayout CreatePlatformView() { _adContainer = new FrameLayout(Context); LoadNativeAd(); return _adContainer; } private void LoadNativeAd() { if (string.IsNullOrEmpty(VirtualView.AdUnitId)) return; var options = new NativeAdLoaderOptions.Builder().Build(); _adLoader = new NativeAdLoader(Context, VirtualView.AdUnitId, new NativeAdListener(this)); _adLoader.LoadAd(new AdRequest.Builder().Build()); } private class NativeAdListener : AdListener { private readonly NativeAdViewHandler _handler; public NativeAdListener(NativeAdViewHandler handler) => _handler = handler; public override void OnAdLoaded(Ad ad) { base.OnAdLoaded(ad); if (ad is NativeAd nativeAd) { _handler._nativeAd = nativeAd; _handler.RenderNativeAd(nativeAd); } } } private void RenderNativeAd(NativeAd nativeAd) { var adView = LayoutInflater.From(Context).Inflate(Resource.Layout.native_ad_layout, _adContainer, false); // 绑定广告内容到布局控件 (adView.FindViewById<TextView>(Resource.Id.ad_headline)).Text = nativeAd.Headline; (adView.FindViewById<TextView>(Resource.Id.ad_body)).Text = nativeAd.Body; (adView.FindViewById<Button>(Resource.Id.ad_call_to_action)).Text = nativeAd.CallToAction; if (nativeAd.Icon?.Drawable != null) (adView.FindViewById<ImageView>(Resource.Id.ad_icon)).SetImageDrawable(nativeAd.Icon.Drawable); (adView.FindViewById<TextView>(Resource.Id.ad_attribution)).Text = $"广告 · {nativeAd.Advertiser}"; _adContainer.RemoveAllViews(); _adContainer.AddView(adView); } protected override void DisconnectHandler() { _nativeAd?.Dispose(); _adLoader?.Dispose(); base.DisconnectHandler(); } }
4. 注册 Handler(MauiProgram.cs)
using Microsoft.Maui.Hosting; using YourAppName; using YourAppName.Droid; namespace YourAppName; public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); }); // 注册原生广告控件的Handler builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler(typeof(NativeAdView), typeof(NativeAdViewHandler)); #endif }); return builder.Build(); } }
5. 在XAML中使用原生广告控件
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourAppName" x:Class="YourAppName.MainPage"> <StackLayout Padding="10"> <!-- 其他页面内容 --> <Label Text="原生广告示例" FontSize="Large" Margin="0,20,0,10"/> <!-- 使用AdMob测试原生广告单元ID,上线替换为你的正式ID --> <local:NativeAdView AdUnitId="ca-app-pub-3940256099942544/2247696110" HeightRequest="300"/> </StackLayout> </ContentPage>
内容的提问来源于stack exchange,提问作者Silny ToJa
相关产品推荐
相关产品推荐

