Tutorial for using Xamarin.Google.UserMessagingPlatform (GDPR) for Google AdMob (Android only)
Tags: xamarin, android, gdpr, privacy
Published: 2022-02-28 18:59:26

> _**Note:** If you need **iOS/MAUI** support, raise your concerns in [GitHub](https://github.com/xamarin/GoogleApisForiOSComponents/issues/628) or Tweet to [David Ortinau](https://twitter.com/davidortinau)._

Loading the GDPR for Google AdMob is a tricky business in Android because [Google's Documentation](https://developers.google.com/admob/ump/android/quick-start) is quite unclear, and the steps are quite messy.

Now, the steps are the following ones:

## AdMob Section

1) Go to your [AdMob account](https://admob.google.com/home/).

2) Go to **Privacy & Messaging** and choose the **phone icon**.

![privacy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhfcc7ztnzqscsiz9e9q.png)

3) Create a **new message** and fill in the required information.

![new message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8ywl5dni6w4c7r18zy6.png)

4) Configure your message:

![message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8s0hmyunvgmo3v171uv5.png)

5) Add your **privacy policy** for your app:

![privacy policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzk2k5s6zs9sg8pd17wb.png)

6) Save it and publish it.

## C# Section

1) Download the [Xamarin.Google.UserMessagingPlatform](https://www.nuget.org/packages/Xamarin.Google.UserMessagingPlatform/) <u>for Android</u> from NuGet.

2) Double-check that your **AndroidManifest.xml** has these two lines:

```xml
<activity android:name="com.google.android.gms.ads.AdActivity" android:value="AD_UNIT_ID" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="APP_ID" />
```

You can get **AD_UNIT_ID** and **APP_ID** from your AdMob account:

![ad unit id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aiff8oeqhsk6dbc3337f.png)

![app id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sliwdmnae52go0mlkqvj.png)
 
3) Load/copy the GDPR code after this line (do not do it before!):

```csharp
MobileAds.Initialize(this);
```

4) Copy and paste this code (based on [JimChapman-4399's version](https://docs.microsoft.com/en-us/answers/questions/481093/guide-for-xamaringoogleusermessagingplatform.html)):

```csharp
private void SetGDPR()
{
    Console.WriteLine("DEBUG: MainActivity.OnCreate: Starting consent management flow, via UserMessagingPlatform.");
    try
    {
#if DEBUG
        var debugSettings = new Xamarin.Google.UserMesssagingPlatform.ConsentDebugSettings.Builder(this)
        .SetDebugGeography(Xamarin.Google.UserMesssagingPlatform.ConsentDebugSettings
                .DebugGeography
                .DebugGeographyEea)
        .AddTestDeviceHashedId(Android.Provider.Settings.Secure.GetString(ContentResolver,
                                            Android.Provider.Settings.Secure.AndroidId))
        .Build();
#endif

        var requestParameters = new Xamarin.Google.UserMesssagingPlatform.ConsentRequestParameters
            .Builder()
            .SetTagForUnderAgeOfConsent(false)
#if DEBUG
            .SetConsentDebugSettings(debugSettings)
#endif
            .Build();

        var consentInformation = Xamarin.Google.UserMesssagingPlatform.UserMessagingPlatform.GetConsentInformation(this);

        consentInformation.RequestConsentInfoUpdate(
            Activity,
            requestParameters,
            new GoogleUMPConsentUpdateSuccessListener(
                () =>
                {
                // The consent information state was updated.
                // You are now ready to check if a form is available.
                if (consentInformation.IsConsentFormAvailable)
                    {
                        Xamarin.Google.UserMesssagingPlatform.UserMessagingPlatform.LoadConsentForm(
                            this,
                            new GoogleUMPFormLoadSuccessListener((Xamarin.Google.UserMesssagingPlatform.IConsentForm f) => {
                                googleUMPConsentForm = f;
                                googleUMPConsentInformation = consentInformation;
                                Console.WriteLine("DEBUG: MainActivity.OnCreate: Consent management flow: LoadConsentForm has loaded a form, which will be shown if necessary, once the ViewModel is ready.");
                                DisplayAdvertisingConsentFormIfNecessary();
                            }),
                            new GoogleUMPFormLoadFailureListener((Xamarin.Google.UserMesssagingPlatform.FormError e) => {
                            // Handle the error.
                            Console.WriteLine("ERROR: MainActivity.OnCreate: Consent management flow: failed in LoadConsentForm with error " + e.Message);
                            }));
                    }
                    else
                    {
                        Console.WriteLine("DEBUG: MainActivity.OnCreate: Consent management flow: RequestConsentInfoUpdate succeeded but no consent form was available.");
                    }
                }),
            new GoogleUMPConsentUpdateFailureListener(
                (Xamarin.Google.UserMesssagingPlatform.FormError e) =>
                {
                // Handle the error.
                Console.WriteLine("ERROR: MainActivity.OnCreate: Consent management flow: failed in RequestConsentInfoUpdate with error " + e.Message);
                })
            );
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR: MainActivity.OnCreate: Exception thrown during consent management flow: ", ex);
    }
}

private Xamarin.Google.UserMesssagingPlatform.IConsentForm googleUMPConsentForm = null;
private Xamarin.Google.UserMesssagingPlatform.IConsentInformation googleUMPConsentInformation = null;
public void DisplayAdvertisingConsentFormIfNecessary()
{
    try
    {
        if (googleUMPConsentForm != null && googleUMPConsentInformation != null)
        {
            /* ConsentStatus:
                Unknown = 0,
                NotRequired = 1,
                Required = 2,
                Obtained = 3
            */
            if (googleUMPConsentInformation.ConsentStatus == 2)
            {
                Console.WriteLine("DEBUG: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Consent form is being displayed.");
                DisplayAdvertisingConsentForm();
            }
            else
            {
                Console.WriteLine("DEBUG: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Consent form is not being displayed because consent status is " + googleUMPConsentInformation.ConsentStatus.ToString());
            }
        }
        else
        {
            Console.WriteLine("ERROR: MainActivity.DisplayAdvertisingConsentFormIfNecessary: consent form or consent information missing.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Exception thrown: ", ex);
    }
}

public void DisplayAdvertisingConsentForm()
{
    try
    {
        if (googleUMPConsentForm != null && googleUMPConsentInformation != null)
        {
            Console.WriteLine("DEBUG: MainActivity.DisplayAdvertisingConsentForm: Consent form is being displayed.");

            googleUMPConsentForm.Show(Activity, new GoogleUMPConsentFormDismissedListener(
                    (Xamarin.Google.UserMesssagingPlatform.FormError f) =>
                    {
                        if (googleUMPConsentInformation.ConsentStatus == 2) // required
                    {
                            Console.WriteLine("ERROR: MainActivity.DisplayAdvertisingConsentForm: Consent was dismissed; showing it again because consent is still required.");
                            DisplayAdvertisingConsentForm();
                        }
                    }));
        }
        else
        {
            Console.WriteLine("ERROR: MainActivity.DisplayAdvertisingConsentForm: consent form or consent information missing.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR: MainActivity.DisplayAdvertisingConsentForm: Exception thrown: ", ex);
    }
}

public class GoogleUMPConsentFormDismissedListener : Java.Lang.Object, Xamarin.Google.UserMesssagingPlatform.IConsentFormOnConsentFormDismissedListener
{
    public GoogleUMPConsentFormDismissedListener(Action<Xamarin.Google.UserMesssagingPlatform.FormError> failureAction)
    {
        a = failureAction;
    }
    public void OnConsentFormDismissed(Xamarin.Google.UserMesssagingPlatform.FormError f)
    {
        a(f);
    }

    private Action<Xamarin.Google.UserMesssagingPlatform.FormError> a = null;
}

public class GoogleUMPConsentUpdateFailureListener : Java.Lang.Object, Xamarin.Google.UserMesssagingPlatform.IConsentInformationOnConsentInfoUpdateFailureListener
{
    public GoogleUMPConsentUpdateFailureListener(Action<Xamarin.Google.UserMesssagingPlatform.FormError> failureAction)
    {
        a = failureAction;
    }
    public void OnConsentInfoUpdateFailure(Xamarin.Google.UserMesssagingPlatform.FormError f)
    {
        a(f);
    }

    private Action<Xamarin.Google.UserMesssagingPlatform.FormError> a = null;
}

public class GoogleUMPConsentUpdateSuccessListener : Java.Lang.Object, Xamarin.Google.UserMesssagingPlatform.IConsentInformationOnConsentInfoUpdateSuccessListener
{
    public GoogleUMPConsentUpdateSuccessListener(Action successAction)
    {
        a = successAction;
    }

    public void OnConsentInfoUpdateSuccess()
    {
        a();
    }

    private Action a = null;
}

public class GoogleUMPFormLoadFailureListener : Java.Lang.Object, Xamarin.Google.UserMesssagingPlatform.UserMessagingPlatform.IOnConsentFormLoadFailureListener
{
    public GoogleUMPFormLoadFailureListener(Action<Xamarin.Google.UserMesssagingPlatform.FormError> failureAction)
    {
        a = failureAction;
    }
    public void OnConsentFormLoadFailure(Xamarin.Google.UserMesssagingPlatform.FormError e)
    {
        a(e);
    }

    private Action<Xamarin.Google.UserMesssagingPlatform.FormError> a = null;
}

public class GoogleUMPFormLoadSuccessListener : Java.Lang.Object, Xamarin.Google.UserMesssagingPlatform.UserMessagingPlatform.IOnConsentFormLoadSuccessListener
{
    public GoogleUMPFormLoadSuccessListener(Action<Xamarin.Google.UserMesssagingPlatform.IConsentForm> successAction)
    {
        a = successAction;
    }
    public void OnConsentFormLoadSuccess(Xamarin.Google.UserMesssagingPlatform.IConsentForm f)
    {
        a(f);
    }

    private Action<Xamarin.Google.UserMesssagingPlatform.IConsentForm> a = null;
}
```

5) Load the GDPR:

```csharp
MobileAds.Initialize(this);
SetGDPR();
```

And that's all!

![preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t1dyl24h6y3mrnqu2669.png)

### Follow me on:

|  Personal  |  LinkedIn  |YouTube|Instagram|Cyber Prophets|Sharing Your Stories|
|:----------|:----------|:------------:|:------------:|:------------:|:------------:|
|[![Personal](https://raw.githubusercontent.com/FANMixco/federiconavarrete/master/img/favicons/favicon.png)](https://federiconavarrete.com)|[![LinkedIn](https://i.stack.imgur.com/idQWu.png)](https://www.linkedin.com/in/federiconavarrete)|[![YouTube](https://i.stack.imgur.com/CFPMR.png)](https://youtube.com/c/FedericoNavarrete)|[![Instagram](https://i.stack.imgur.com/PIfqY.png)](https://www.instagram.com/federico_the_consultant)|[![RedCircle Podcast](https://i.stack.imgur.com/4XICF.png)](https://redcircle.com/shows/cyber-prophets)|[![RedCircle Podcast](https://i.stack.imgur.com/4XICF.png)](https://redcircle.com/shows/sharing-your-stories)|

[![sponsor me](https://raw.githubusercontent.com/FANMixco/Xamarin-SearchBar/master/bmc-rezr5vpd.gif)](https://www.buymeacoffee.com/fanmixco)

> **Note:**

> _If you need **iOS/MAUI support**, raise your concerns in [GitHub](https://github.com/xamarin/GoogleApisForiOSComponents/issues/628) or Tweet to [David Ortinau](https://twitter.com/davidortinau). You can also email David at: [David.Ortinau@microsoft.com](David.Ortinau@microsoft.com). They are the only ones who can support and fix these outdated libraries. You can also try to bind and commit your changes to GitHub and support the community. If Microsoft sees there is some real interest, probably, they will do something, but **you the affected one must dare to contact them via their official channels.**_

> _**Anything related to Apple is outside of my scope for now. So, I cannot reply to questions about iOS/macOS coding or specific issues. This article is for Android only.**_