Guide for Xamarin.Google.UserMessagingPlatform?

861 Views Asked by At

I am in the final stages of setting up my Android App using Xamarin / C#. I have implemented Google Admob but GDPR rules say that I must have a privacy notice to display ads. Google's documentation says that the Consent SDK is deprecated and that I should use the new User Messaging Platform https://developers.google.com/admob/ump/android/quick-start

I have downloaded the Nuget package Xamarin.Google.UserMessagingPlatform (https://www.nuget.org/packages/Xamarin.Google.UserMessagingPlatform/1.0.0?_src=template) and have imported the libraries but I am struggling to translate Google's code to my project and having searched online there does not appear to be a live documentation link anywhere with examples of implementation in C# / Xamarin. The project site on the package URL 404s and the source repository leads to the general Xamarin repository but I couldn't find a reference to UMP in there.

Specifically, one statement I do not know how to handle is this:

new ConsentInformation.OnConsentInfoUpdateSuccessListener() {
            @Override
            public void onConsentInfoUpdateSuccess() {
                // The consent information state was updated.
                // You are now ready to check if a form is available.
            }
        },
        new ConsentInformation.OnConsentInfoUpdateFailureListener() {
            @Override
            public void onConsentInfoUpdateFailure(FormError formError) {
                // Handle the error.
            }

Are there any examples of the implementation in C#?

2

There are 2 best solutions below

9
On BEST ANSWER

Note: If you need iOS/MAUI support, raise your concerns in GitHub and/or Tweet to David Ortinau.

I wrote this full tutorial in my blog (for Android only), but here you have it:

AdMob Section

  1. Go to your AdMob account.

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

privacy

  1. Create a new message and fill in the required information.

new message

  1. Configure your message:

message

  1. Add your privacy policy for your app:

privacy policy

  1. Save it and publish it.

C# Section

  1. Download the Xamarin.Google.UserMessagingPlatform from NuGet.

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

<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:

  1. Load/copy the GDPR code after this line (do not do it before!):
MobileAds.Initialize(this);
  1. Copy and paste this code:
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(this.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(Context);

        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(
                            Context,
                            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;
}
  1. Load the GDPR:
MobileAds.Initialize(this);
SetGDPR();

And that's all!

preview

1
On

In MainActivity.OnCreate, some time after the call to base.OnCreate(bundle); insert this code snippet:

        App.LogMessage("DEBUG: MainActivity.OnCreate: Starting consent management flow, via UserMessagingPlatform.");
        try
        {
            ConsentRequestParameters requestParameters = new ConsentRequestParameters
                .Builder()
                .SetTagForUnderAgeOfConsent(false)
                .Build();

            IConsentInformation consentInformation = UserMessagingPlatform.GetConsentInformation(this);

            consentInformation.RequestConsentInfoUpdate(
                this,
                requestParameters,
                new GoogleUMPConsentUpdateSuccessListener(
                    () =>
                    {
                        // The consent information state was updated.
                        // You are now ready to check if a form is available.
                        if (consentInformation.IsConsentFormAvailable)
                        {
                            UserMessagingPlatform.LoadConsentForm(
                                this,
                                new GoogleUMPFormLoadSuccessListener((IConsentForm f)=> {
                                    this.googleUMPConsentForm = f;
                                    this.googleUMPConsentInformation = consentInformation;
                                    App.LogMessage("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((FormError e)=> {
                                    // Handle the error.
                                    App.LogMessage("ERROR: MainActivity.OnCreate: Consent management flow: failed in LoadConsentForm with error " + e.Message);
                                }));
                        }
                        else
                        {
                            App.LogMessage("DEBUG: MainActivity.OnCreate: Consent management flow: RequestConsentInfoUpdate succeeded but no consent form was available.");
                        }
                    }),
                new GoogleUMPConsentUpdateFailureListener(
                    (FormError e) =>
                    {
                        // Handle the error.
                        App.LogMessage("ERROR: MainActivity.OnCreate: Consent management flow: failed in RequestConsentInfoUpdate with error " + e.Message);
                    })
                );
        }
        catch (Exception ex)
        {
            App.LogMessage("ERROR: MainActivity.OnCreate: Exception thrown during consent management flow: ", ex);
        }

Then, in the body of the MainActivity class, you will also need to add these definitions:

    private IConsentForm googleUMPConsentForm = null;
    private 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)
                {
                    App.LogMessage("DEBUG: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Consent form is being displayed.");
                    DisplayAdvertisingConsentForm();
                }
                else
                {
                    App.LogMessage("DEBUG: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Consent form is not being displayed because consent status is "+ googleUMPConsentInformation.ConsentStatus.ToString());
                }
            }
            else
            {
                App.LogMessage("ERROR: MainActivity.DisplayAdvertisingConsentFormIfNecessary: consent form or consent information missing.");
            }
        }
        catch(Exception ex)
        {
            App.LogMessage("ERROR: MainActivity.DisplayAdvertisingConsentFormIfNecessary: Exception thrown: ", ex);
        }
    }

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

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

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

        private Action<FormError> a = null;
    }


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

        private Action<FormError> a = null;
    }

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

        public void OnConsentInfoUpdateSuccess()
        {
            a();
        }

        private Action a = null;
    }

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

        private Action<FormError> a = null;
    }

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

        private Action<IConsentForm> a = null;
    }