Neste artigo veremos como monetizar o seu aplicativo Xamarin.Forms, adicionando propaganda com a plataforma AdMob by Google.
Atualmente a AdMob by Google é suportada apenas pelas plataformas Android e iOS.
Criando uma conta na AdMob
É necessário criar uma conta na AdMob, para isso acesse: https://apps.admob.com/signup.
Após criar uma conta, clique em “Primeiros Passos” e crie um novo aplicativo, no término da criação do aplicativo você receberá um Id nesse formato: ca-app-pub-XXXXXXXXXXXXXXXX / XXXXXXXXXX. Guarde esse Id, será utilizado a seguir.
Observação: É necessário um Id para Android e outro para iOS, então você precisará criar dois aplicativos na AdMob.
Criando um bloco de anúncios
Para este exemplo o bloco escolhido foi o Banner.
O processo de criação do bloco de anúncios demora um tempo, então pode ser que você receba a seguinte mensagem de erro: “Ocorreu um problema ao obter uma resposta do anúncio. ErrorCode: 0 Falha ao carregar o anúncio: 0“. Não se preocupe, isso significa que o bloco de anúncios ainda está em processo de criação.
Para fins de testes, a AdMob fornece alguns anúncios:
Xamarin.Forms
AdMobView
Crie a classe AdMobView com a propriedade AdUnitId do tipo string , como demonstrado a seguir.
using Xamarin.Forms; | |
namespace DemoAdMob | |
{ | |
public class AdMobView : View | |
{ | |
public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create( | |
nameof(AdUnitId), | |
typeof(string), | |
typeof(AdMobView), | |
string.Empty); | |
public string AdUnitId | |
{ | |
get => (string)GetValue(AdUnitIdProperty); | |
set => SetValue(AdUnitIdProperty, value); | |
} | |
} | |
} |
Xaml
No Xaml crie um AdMobView e posicione onde desejar.
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
xmlns:local="clr-namespace:DemoAdMob" | |
x:Class="DemoAdMob.MainPage"> | |
<StackLayout> | |
<local:AdMobView x:Name="adMobView" | |
VerticalOptions="EndAndExpand"/> | |
</StackLayout> | |
</ContentPage> |
C#
Para fins apenas de exemplificação esse código foi adicionado no CodeBehind, mas você também pode coloca-lo em uma ViewModel.
Realize a verificação de qual plataforma está sendo utilizada e adicione o Id referente a plataforma na propriedade AdUnitId do AdMobView criado anteriormente.
using Xamarin.Forms; | |
namespace DemoAdMob | |
{ | |
public partial class MainPage : ContentPage | |
{ | |
public MainPage() | |
{ | |
InitializeComponent(); | |
BindingContext = this; | |
if (Device.RuntimePlatform == Device.Android) | |
adMobView.AdUnitId = "SEU ID ANDROID"; | |
else if (Device.RuntimePlatform == Device.iOS) | |
adMobView.AdUnitId = "SEU ID iOS"; | |
} | |
} | |
} |
Android
Em seu projeto Android, instale o Nuget Package Xamarin.Firebase.Ads.
Observação: Instale uma versão anterior da atual, devido a alguma incompatibilidades com a versão do Xamarin.Forms.
MainActivity
Na MainActivity inicialize o plugin após “base.OnCreate(bundle)”.
using Android.App; | |
using Android.Content.PM; | |
using Android.Gms.Ads; | |
using Android.OS; | |
namespace DemoAdMob.Droid | |
{ | |
[Activity(Label = "DemoAdMob", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] | |
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity | |
{ | |
protected override void OnCreate(Bundle bundle) | |
{ | |
TabLayoutResource = Resource.Layout.Tabbar; | |
ToolbarResource = Resource.Layout.Toolbar; | |
base.OnCreate(bundle); | |
MobileAds.Initialize(ApplicationContext, "SEU ID ANDROID"); | |
global::Xamarin.Forms.Forms.Init(this, bundle); | |
LoadApplication(new App()); | |
} | |
} | |
} | |
Permissões
Acesse as propriedades do projeto Android, na aba Android Manifest adicione as seguintes permissões (ACCESS_NETWORK_STATE e INTERNET).
AndroidManifest.xml
Edite o arquivo AndroidManifest.xml e entre as Tags “manifest” adicione a seguinte linha.
<?xml version="1.0" encoding="utf-8"?> | |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.DemoAdMob" android:installLocation="auto"> | |
<uses-sdk android:minSdkVersion="15" /> | |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<application android:label="DemoAdMob.Android"></application> | |
<activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" /> | |
</manifest> |
AdMobViewRenderer
O último passo para o projeto Android é adicionar um CustomRenderer, para isso crie uma classe chamada “AdMobViewRenderer” como demonstrado a seguir.
using System.ComponentModel; | |
using DemoAdMob; | |
using DemoAdMob.Droid; | |
using Android.Content; | |
using Android.Gms.Ads; | |
using Android.Widget; | |
using Xamarin.Forms; | |
using Xamarin.Forms.Platform.Android; | |
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))] | |
namespace DemoAdMob.Droid | |
{ | |
public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView> | |
{ | |
public AdMobViewRenderer(Context context) : base(context) { } | |
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e) | |
{ | |
base.OnElementChanged(e); | |
if (e.NewElement != null && Control == null) | |
{ | |
SetNativeControl(CreateAdView()); | |
} | |
} | |
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) | |
{ | |
base.OnElementPropertyChanged(sender, e); | |
if (e.PropertyName == nameof(AdView.AdUnitId)) | |
Control.AdUnitId = Element.AdUnitId; | |
} | |
private AdView CreateAdView() | |
{ | |
var adView = new AdView(Context) | |
{ | |
AdSize = AdSize.SmartBanner, | |
AdUnitId = Element.AdUnitId | |
}; | |
adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); | |
adView.LoadAd(new AdRequest.Builder().Build()); | |
return adView; | |
} | |
} | |
} |
iOS
Em seu projeto iOS, instale o Nuget Package Xamarin.Firebase.iOS.AdMob.
AppDelegate
No arquivo AppDelegate.cs no método FinishedLaunching inicialize o Nuget Package como demonstrado a seguir.
using Foundation; | |
using UIKit; | |
namespace DemoAdMob.iOS | |
{ | |
// The UIApplicationDelegate for the application. This class is responsible for launching the | |
// User Interface of the application, as well as listening (and optionally responding) to | |
// application events from iOS. | |
[Register("AppDelegate")] | |
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate | |
{ | |
// | |
// This method is invoked when the application has loaded and is ready to run. In this | |
// method you should instantiate the window, load the UI into it and then make the window | |
// visible. | |
// | |
// You have 17 seconds to return from this method, or iOS will terminate your application. | |
// | |
public override bool FinishedLaunching(UIApplication app, NSDictionary options) | |
{ | |
Google.MobileAds.MobileAds.Configure("SEU ID iOS"); | |
global::Xamarin.Forms.Forms.Init(); | |
LoadApplication(new App()); | |
return base.FinishedLaunching(app, options); | |
} | |
} | |
} |
AdMobViewRenderer
E para finalizar adicione um CustomRenderer, para isso crie uma classe chamada “AdMobViewRenderer” como demonstrado a seguir.
using DemoAdMob; | |
using DemoAdMob.iOS; | |
using Google.MobileAds; | |
using System.ComponentModel; | |
using UIKit; | |
using Xamarin.Forms; | |
using Xamarin.Forms.Platform.iOS; | |
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))] | |
namespace DemoAdMob.iOS | |
{ | |
public class AdMobViewRenderer : ViewRenderer<AdMobView, BannerView> | |
{ | |
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e) | |
{ | |
base.OnElementChanged(e); | |
if (Control == null) | |
{ | |
SetNativeControl(CreateBannerView()); | |
} | |
} | |
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) | |
{ | |
base.OnElementPropertyChanged(sender, e); | |
if (e.PropertyName == nameof(BannerView.AdUnitID)) | |
Control.AdUnitID = Element.AdUnitId; | |
} | |
private BannerView CreateBannerView() | |
{ | |
var bannerView = new BannerView(AdSizeCons.SmartBannerPortrait) | |
{ | |
AdUnitID = Element.AdUnitId, | |
RootViewController = GetVisibleViewController() | |
}; | |
bannerView.LoadRequest(GetRequest()); | |
Request GetRequest() | |
{ | |
var request = Request.GetDefaultRequest(); | |
return request; | |
} | |
return bannerView; | |
} | |
private UIViewController GetVisibleViewController() | |
{ | |
var windows = UIApplication.SharedApplication.Windows; | |
foreach (var window in windows) | |
{ | |
if (window.RootViewController != null) | |
{ | |
return window.RootViewController; | |
} | |
} | |
return null; | |
} | |
} | |
} |
Resultado
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.
Se possível, ensinasse como faz no uwp, assim , não consegui, um passo a passo melhor.
https://montemagno.com/xamarin-forms-uwp-ads/
CurtirCurtir