원본

https://www.xamarinexpert.it/admob-made-easy/

 

 

In this tutorial I’ll show you how to monetize your Xamarin apps with AdMob using my MTAdmob plugin.

Important: If you receive errors compiling the code for iOS, install the package Xamarin.Google.iOS.MobileAds in your iOS project.

UPDATE 1/May/2019: I’ve released the new version 1.3 thas sovles some issues with iOS and improves performances.

UPDATE: From version 1.2, MTAdmob supports also Google ads rewarded videos for Android and iOS

UPDATE: I’ve added on github the source code of a project to test this Admob plugin. You can find it here: https://github.com/marcojak/TestMTAdmob

To help you to speed up your Xamarin development, I’ve created a set of plugins, one of them is MTAdmob. Thanks to this plugin you can add Admob banners and Insterstitials in just few lines of code. It couldn’t be easier than that and I’ll show you.

Install the plugin

First of all, right click on your Xamarin solution and select “Manage Nuget packages for Solution”

Visual Studio will open a new screen where you can search and install one or more nuget packages. In this case we can search for the MTAdmob plugin. Searching for MarcTron will show you all my packages (I’m sure you can find other useful plugins that I’ve written), and we can select the MTAdmob plugin as showed in the next image.

It’s very important that you install the plugin in your PCL/.Net standard project and in your platform projects (Android, iOS, UWP).

After the Admob plugin is installed we can add banners and insterstitials to our projects.

Add Ads to our project

With version 1.0 the MTAdmob plugin supports banner and interstitials for Android and iOS. If you would like to see the plugin supporting also the UWP platform, let me now and I’ll add the support in a new version.

As I’ve said we can add Banners and Interstitials Admob ads to our project. Let’s start with the Banners

How to add an Admob Banner

An Admob banner is just a view inside our page. It means that we can add it using XAML or C#. First of all let’s see how to add an Admob banner using XAML.

Add an Admob Banner with XAML

In MTAdmob to use an Admob banner I’ve created a custom control called AdView, so to use it we can use this code:

<?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:controls="clr-namespace:MarcTron.Plugin.Controls;assembly=Plugin.MtAdmob"

             x:Class="Test.MTAdmob.MainPage">

 

<StackLayout>

    <Label Text="Let's test an Admob Banner!"

           HorizontalOptions="Center"

           VerticalOptions="CenterAndExpand" />

    <!-- Place the Admob controls here -->

    <controls:MTAdView></controls:MTAdView>

</StackLayout>

In this example we have created a StackLayout with 2 controls: a label and an AdView (our Admob banner). Easy! Isn’t it???

The AdView control is basically a View so you can use all the properties you can think of like: HorizontalOptions, VerticalOptions, IsVisible…

In addition to these properties, I’ve added in AdView two other properties: AdsId and PersonalizedAds.

AdsId: Allows you to add the Banner Id (you can find it in your Admob account)

PersonalizedAds: This allow you to use non personalized ads. For example in case of GPDR. Of course it’s better to use personalized Ads.

To use these properties you can update the previous code to:

<controls:AdView PersonalizedAds="true" AdsId="xxxxxxxxxxxxxxxxxx"></controls:AdView>

Add an Admob Banner with C#

In case you don’t write your pages with XAML or you write your UI in C# or you want to add your view only in some cases, you can add your Admob Banner using this code:

using MarcTron.Plugin;

...

MTAdView ads = new MTAdView();

Of course you need to attach this View to your layout, but you know how to do it (If not, feel free to ask).

To use the custom properties you can change the previous code to:

...

MTAdView ads = new MTAdView();

ads.AdsId = "xxx";

ads.PersonalizedAds = true;

Also in this case, to add an Admob banner is INCREDIBILY EASY!!!

Global Custom Properties

As you have seen, the properties AdsId and PersonalizedAds belong to a single AdView. It means that you have to set them for every Admob Banner.

To make things even easier I’ve added the option to set these properties only once. To do so, you can use this C# code:

CrossMTAdmob.Current.UserPersonalizedAds = true;

CrossMTAdmob.Current.AdsId = "xxxxxxxxxxxxxxxx";

In this case all your Admob banner will show personalized ads and will have the same Id.

If you set local and global properties, the local ones will have higher priority.

Use of Banner Events

I’ve added 4 events to the Admob banner that you could find nice to have. These events are:

  • AdsClicked When a user clicks on the ads
  • AdsClosed When the user closes the ads
  • AdsImpression Called when an impression is recorded for an ad.
  • AdsOpened When the ads is opened

To use these events you can write this code:

AdView myAds = new AdView();

myAds.AdsClicked += MyAdsAdsClicked;

myAds.AdsClosed += MyAds_AdVClosed;

myAds.AdsImpression += MyAds_AdVImpression;

myAds.AdsOpened += MyAds_AdVOpened;

Of course you can use these events also if you have declared your AdView in your XAML code.

Admob Interstitials

Now that we know how to add Admob banners using my plugin MTAdmob, let’s see how we can add Admob Interstitials. If possible, to add an Admob interstitial is even easier. You just need a single line of code. Don’t you believe me? Look here how to show an Admob interstitial:

CrossMTAdmob.Current.ShowInterstitial("ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx");

I told you!!! That’s it!!! With that line of code you have just showed an Interstitial in you app. Of course you need to replace that string with the Insterstitial ID you can find in your Admob account.

Events for Interstitials

There 3 events that you can use with Interstitials:

OnInterstitialLoaded        When it's loaded

OnInterstitialOpened        When it's opened      

OnInterstitialClosed        When it's closed

Rewarded Video

From version 1.1 the plugin supports the amazing Rewarded Video too.

To show a rewarded video you just need a single line of code:

CrossMTAdmob.Current.ShowRewardedVideo("xx-xxx-xxx-xxxxxxxxxxxxxxxxx/xxxxxxxxxx");

Events for Rewarded videos

There are 7 events that you can use with the Rewarded video Ads:

OnRewarded                          When the user gets a reward

OnRewardedVideoAdClosed             When the ads is closed

OnRewardedVideoAdFailedToLoad       When the ads fails to load

OnRewardedVideoAdLeftApplication    When the users leaves the application

OnRewardedVideoAdLoaded             When the ads is loaded

OnRewardedVideoAdOpened             When the ads is opened

OnRewardedVideoStarted              When the ads starts

Initialization

Before you can use the Admob banners and Interstitials, you need to initialize it. You need to do it only once so it makes sense to initialize it onside the OnCreate method in Android and FinishedLaunching in iOS.

In your Android project add this line in your OnCreate method:

MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

In your iOS project add this line in your FinishedLaunching method:

MobileAds.Configure("ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

If you receive errors compiling the code for iOS, install the package Xamarin.Google.iOS.MobileAds in your iOS project.

ANDROID PROJECT (IMPORTANT)

In your AndroidManifest you should add these lines:

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

<application android:label="Test.MTAdmob.Android">

    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>

    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />

</application>

Some useful links

Conclusion

This Admob MTAdmob plugin is incredibly easy to use but in case you need help, or you want to suggest a new feature or for any other reason, write me.

 

xaml 단에서 아래처럼 선언했는데 광고가 표시가 되지 않았다.

<lottomanager:AdBanner x:Name="adBanner" Size="Standardbanner" WidthRequest="320" HeightRequest="50" BackgroundColor="Black" VerticalOptions="EndAndExpand"/>

 

확인해 보니 코드 단에서 아래 처럼 처리하면 광고가 제대로 나타나는걸 확인!! @.@

 

 

  protected override void OnAppearing()

        {

            base.OnAppearing();

 

            if (Device.RuntimePlatform == Device.Android)

            {

                Device.BeginInvokeOnMainThread(() =>

                {

                    this.adBanner.IsVisible = false;

                    this.adBanner.IsVisible = true;

                });

            }

        }

 

      

 

참고

https://forums.xamarin.com/discussion/145122/admob-appears-only-after-rotation

아래처럼 빌드시에는 이상이 없었는데

기기로 디버깅 시 에러가 발생되었다.

 

System.TypeLoadException: Could not load type of field 'Xamarin.Forms.Platform.Android.RendererPool:_freeRenderers' (0) due to: Could not resolve type with token 010001b1 from typeref (expected class 'System.Collections.Generic.Stack`1' in assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e') assembly:mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e type:System.Collections.Generic.Stack`1 member:(null)

 

찾아보니 Forms 버전을 다운 그레이드 하면 해결되는데 (4.1.0.778454 버전으로 다운 그레이드)

 

 

Android 쪽 패키들과 버전 충돌때문에 다운그레이드가 잘되지 않았다. ㅠㅜ

 

 

그래서 위 목록을 모두 제거하고 Forms 버전은 4.1.0.778454 으로 설치

나머지 Android 쪽 패키지들은 28.0.0.1 (낮은)버전으로 설치하고 실행하니 정상적으로 동작되었다.

 

아래는 재설치후 버전들..

 

 

 

 

 

https://robgibbens.com/deploying-a-database-file-with-a-xamarin-forms-app/

https://csharp.hotexamples.com/examples/ZXing.Net.Mobile.Forms/ZXingScannerPage/-/php-zxingscannerpage-class-examples.html



기존에 사용했던 코드가

public static readonly BindableProperty SpacingProperty =

    BindableProperty.Create<WrapLayout, double>(w => w.Spacing, 5,

        propertyChanged: (bindable, oldvalue, newvalue) => ((WrapLayout)bindable).layoutCache.Clear());

 

아래처럼 줄이 그어져 확인해보니


"Create<> (generic) is obsolete as of version 2.1.0 and is no longer supported."

 

위 문구 처럼 Create<> 는 더 이상 지원하지 않는다고한다.

 

위 내용을 지원되는 현재 버전으로 변경하면 아래와 같다.

 

public static readonly BindableProperty SpacingProperty =

    BindableProperty.Create(nameof(Spacing), typeof(double), typeof(WrapLayout), 5.0,

        propertyChanged: (bindable, oldValue, newValue) => ((WrapLayout)bindable).layoutCache.Clear());

 

 

참고

https://forums.xamarin.com/discussion/comment/177726/#Comment_177726

https://forums.xamarin.com/discussion/62984/generic-versions-of-create-are-no-longer-supported-and-deprecated

 

 

BindableProperty.Create<BindablePicker, IList>(p => p.ItemsSource, null,

    propertyChanged: OnItemsSourcePropertyChanged);

=>

BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,

    propertyChanged: OnItemsSourcePropertyChanged);

 

 

private static void OnItemsSourcePropertyChanged(BindableObject bindable, IList oldValue, IList newValue)

=>

private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)

 

 

var tgr = new TapGestureRecognizer { NumberOfTapsRequired = 1 };

tgr.Tapped += (sender, args) =>

{

    // 처리할 내용

};

 

this.grid.GestureRecognizers.Add(tgr);

 

 

- NumberOfTapsRequired : tab수로 2로 설정한 경우 두번 tab 한 경우 이벤트가 발생된다.

 

위와 같은 형식으로 Image 도 아래처럼 Click 이벤트를 처리할수 있다.

 

var tgr = new TapGestureRecognizer { NumberOfTapsRequired = 1 };

tgr.Tapped += (sender, args) =>

{

    // 처리할 내용

};

 

this.image.GestureRecognizers.Add(tgr);

 

 

 

xaml 로 처리할때

 

<Label>

    <Label.GestureRecognizers>

        <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>

    </Label.GestureRecognizers>

</Label>

앱을 등록하면 아래와 같이 64 비트 요구사항을 준수하지 않는다는 문구가 뜬다.

 

이를 위해선 프로젝트 속성의 Android 옵션 에서 고급 버튼을 클릭하고

'지원되는 아키텍처'의 arm64-v8a 를 체크하고 빌드하면 된다.

 

 

참고

https://developer.android.com/distribute/best-practices/develop/64-bit

웹뷰에 특정 사이트를 나타내도록 했는데

아래 처럼 에러가 발생되었다.

 

 

ERR_CLEARTEXT_NOT_PERMITTED 로 찾아보니 https 가 아닌 주소인 경우 위처럼 에러가 발생될수 있다고 한다.

위 에러 해결을 위해선 Android 프로젝트의 AndroidManifest.xml 파일의 application  에 아래와 같이

android:usesCleartextTraffic="true" 값을 넣어주면 된다.

 

앞서 만들어진 프로비전 프로필을 프로젝트에 적용하는 방법입니다.

(윈도우에서 처리하는 방법입니다.)

 

iOS 프로젝트 속성의 iOS 번들 서명에서 앞서 등록했던 프로비전 프로필이 목록에 나타나지 않습니다.

 

이를 나타내기 위해선 Visual Studio 의 도구 > 옵션을 클릭

 

Xamarin > Apple Account 를 클릭합니다.

 

 

여기에서 유의사항은 이때 Mac 에 비번을 입력해야합니다.

항상 허용을 하면 다음부터 물어보지 않습니다.

(가끔 비쥬얼 스튜디오가 반응이 없을땐 Mac 을 확인해주세요. 항상허용을 하더라도 물어볼때도 있음.)