Comenzar

Según la Política de Consentimiento de Usuarios de la UE de Google, debes divulgar cierta información a los usuarios del Espacio Económico Europeo (EEE) y el Reino Unido, y obtener su consentimiento para usar cookies y otro tipo de almacenamiento local, cuando sea un requisito legal, así como utilizar datos personales (como el ID del anuncio) para publicar anuncios. Esta política refleja los requisitos de la Directiva de Privacidad Electrónica de la UE y el Reglamento General de Protección de Datos (GDPR).

Para ayudar a los publicadores a cumplir con sus obligaciones en virtud de esta política, Google ofrece el SDK de User Messaging Platform (UMP). El SDK de UMP se actualizó para ser compatible con los estándares más recientes de la IAB. Todas estas configuraciones ahora se pueden controlar de forma conveniente en AdMob la privacidad y la mensajería.

Requisitos previos

Cómo crear un tipo de mensaje

Crea mensajes para los usuarios con uno de los tipos de mensajes disponibles para los usuarios en la pestaña Privacidad y mensajería de tu cuenta deAdMob . El SDK de UMP intenta mostrar un mensaje del usuario creado a partir del AdMob ID de aplicación configurado en tu proyecto. Si no se configura ningún mensaje para tu aplicación, el SDK muestra un error.

Para obtener más detalles, consulta Acerca de la privacidad y la mensajería.

Cómo realizar la instalación con Gradle

Agrega la dependencia para el SDK de Google User Messaging Platform al archivo Gradle a nivel de la app de tu módulo, que suele ser app/build.gradle:

dependencies {
  implementation 'com.google.android.ump:user-messaging-platform:2.1.0'
}

Después de realizar los cambios en el archivo build.gradle de tu app, asegúrate de sincronizar el proyecto con los archivos de Gradle.

Debes solicitar una actualización de la información de consentimiento del usuario en cada lanzamiento de la app mediante requestConsentInfoUpdate(). Esto determina si el usuario debe dar su consentimiento si aún no lo hizo o si venció.

Este es un ejemplo de cómo verificar el estado de MainActivity en el método onCreate().

Java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.FormError;
import com.google.android.ump.UserMessagingPlatform;

public class MainActivity extends AppCompatActivity {
  private ConsentInformation consentInformation;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build();

    consentInformation = UserMessagingPlatform.getConsentInformation(this);
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        (OnConsentInfoUpdateSuccessListener) () -> {
          // TODO: Load and show the consent form.
        },
        (OnConsentInfoUpdateFailureListener) requestConsentError -> {
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.getErrorCode(),
              requestConsentError.getMessage()));
        });
  }
}

Kotlin

package com.example.myapplication

import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentInformation.OnConsentInfoUpdateFailureListener
import com.google.android.ump.ConsentInformation.OnConsentInfoUpdateSuccessListener
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.UserMessagingPlatform

class MainActivity : AppCompatActivity() {
  private lateinit var consentInformation: ConsentInformation

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    val params = ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build()

    consentInformation = UserMessagingPlatform.getConsentInformation(this)
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        ConsentInformation.OnConsentInfoUpdateSuccessListener {
          // TODO: Load and show the consent form.
        },
        ConsentInformation.OnConsentInfoUpdateFailureListener {
          requestConsentError ->
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.errorCode(),
              requestConsentError.message()))
        })
  }
}

Carga y muestra un formulario de consentimiento si es necesario

Una vez que hayas recibido el estado de consentimiento más actualizado, llama aloadAndShowConsentFormIfRequired() en la claseConsentForm para cargar un formulario de consentimiento. Si el estado de consentimiento es obligatorio, el SDK carga un formulario y lo presenta de inmediato desde el activityproporcionado. Se llama a callbackdespués de descartar el formulario. Si no se requiere consentimiento, se llama a callbackde inmediato.

Java

public class MainActivity extends AppCompatActivity {
  private ConsentInformation consentInformation;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build();

    consentInformation = UserMessagingPlatform.getConsentInformation(this);
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        (OnConsentInfoUpdateSuccessListener) () -> {
          UserMessagingPlatform.loadAndShowConsentFormIfRequired(
            this,
            (OnConsentFormDismissedListener) loadAndShowError -> {
              if (loadAndShowError != null) {
                // Consent gathering failed.
                Log.w(TAG, String.format("%s: %s",
                    loadAndShowError.getErrorCode(),
                    loadAndShowError.getMessage()));
              }

              // Consent has been gathered.
            }
          )
        },
        (OnConsentInfoUpdateFailureListener) requestConsentError -> {
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.getErrorCode(),
              requestConsentError.getMessage()));
        });
  }
}

Kotlin

class MainActivity : AppCompatActivity() {
  private lateinit var consentInformation: ConsentInformation

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    val params = ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build()

    consentInformation = UserMessagingPlatform.getConsentInformation(this)
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        ConsentInformation.OnConsentInfoUpdateSuccessListener {
          UserMessagingPlatform.loadAndShowConsentFormIfRequired(
            this@MainActivity,
            ConsentForm.OnConsentFormDismissedListener {
              loadAndShowError ->
              // Consent gathering failed.
              Log.w(TAG, String.format("%s: %s",
                  loadAndShowError.errorCode(),
                  loadAndShowError.message()))

              // Consent has been gathered.
            }
          )
        },
        ConsentInformation.OnConsentInfoUpdateFailureListener {
          requestConsentError ->
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.errorCode(),
              requestConsentError.message()))
        })
  }
}

Si necesitas realizar alguna acción después de que el usuario haya elegido o descartado el formulario, coloca esa lógica en el callbackde tu formulario.

Solicitar anuncios

Antes de solicitar anuncios en tu app, verifica si obtuviste el consentimiento del usuario que usa canRequestAds(). Hay dos lugares que debes verificar cuando obtienes el consentimiento:

  1. Una vez que se haya obtenido el consentimiento en la sesión actual.
  2. Inmediatamente después de llamar a requestConsentInfoUpdate(). Es posible que se haya obtenido el consentimiento en la sesión anterior. Como práctica recomendada de latencia, te sugerimos no esperar a que se complete la devolución de llamada para que puedas comenzar a cargar anuncios lo antes posible después del lanzamiento de tu app.
.

Si se produce un error durante el proceso de obtención de consentimiento, aún debes intentar solicitar anuncios. El SDK de UMP usa el estado de consentimiento de la sesión anterior.

Java

public class MainActivity extends AppCompatActivity {
  private ConsentInformation consentInformation;
  // Use an atomic boolean to initialize the Google Mobile Ads SDK and load ads once.
  private final AtomicBoolean isMobileAdsInitializeCalled = new AtomicBoolean(false);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build();

    consentInformation = UserMessagingPlatform.getConsentInformation(this);
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        (OnConsentInfoUpdateSuccessListener) () -> {
          UserMessagingPlatform.loadAndShowConsentFormIfRequired(
            this,
            (OnConsentFormDismissedListener) loadAndShowError -> {
              if (loadAndShowError != null) {
                // Consent gathering failed.
                Log.w(TAG, String.format("%s: %s",
                    loadAndShowError.getErrorCode(),
                    loadAndShowError.getMessage()));
              }

              // Consent has been gathered.
              if (consentInformation.canRequestAds) {
                initializeMobileAdsSdk();
              }
            }
          )
        },
        (OnConsentInfoUpdateFailureListener) requestConsentError -> {
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.getErrorCode(),
              requestConsentError.getMessage()));
        });

    // Check if you can initialize the Google Mobile Ads SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if (consentInformation.canRequestAds) {
      initializeMobileAdsSdk();
    }
  }

  private void initializeMobileAdsSdk() {
    if (isMobileAdsInitializeCalled.getAndSet(true)) {
      return;
    }

    // Initialize the Google Mobile Ads SDK.
    MobileAds.initialize(this);

    // TODO: Request an ad.
    // InterstitialAd.load(...);
  }
}

Kotlin

class MainActivity : AppCompatActivity() {
  private lateinit var consentInformation: ConsentInformation
  // Use an atomic boolean to initialize the Google Mobile Ads SDK and load ads once.
  private var isMobileAdsInitializeCalled = AtomicBoolean(false)

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Set tag for under age of consent. false means users are not under age
    // of consent.
    val params = ConsentRequestParameters
        .Builder()
        .setTagForUnderAgeOfConsent(false)
        .build()

    consentInformation = UserMessagingPlatform.getConsentInformation(this)
    consentInformation.requestConsentInfoUpdate(
        this,
        params,
        ConsentInformation.OnConsentInfoUpdateSuccessListener {
          UserMessagingPlatform.loadAndShowConsentFormIfRequired(
            this@MainActivity,
            ConsentForm.OnConsentFormDismissedListener {
              loadAndShowError ->
              // Consent gathering failed.
              Log.w(TAG, String.format("%s: %s",
                  loadAndShowError.errorCode(),
                  loadAndShowError.message()))

              // Consent has been gathered.
              if (consentInformation.canRequestAds) {
                initializeMobileAdsSdk()
              }
            }
          )
        },
        ConsentInformation.OnConsentInfoUpdateFailureListener {
          requestConsentError ->
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.errorCode(),
              requestConsentError.message()))
        })

    // Check if you can initialize the Google Mobile Ads SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if (consentInformation.canRequestAds) {
      initializeMobileAdsSdk()
    }
  }

  private fun initializeMobileAdsSdk() {
    if (isMobileAdsInitializeCalled.get()) {
      return
    }
    isMobileAdsInitializeCalled.set(true)

    // Initialize the Google Mobile Ads SDK.
    MobileAds.initialize(this)

    // TODO: Request an ad.
    // InterstitialAd.load(...)
  }
}

Pruebas

Si quieres probar la integración en tu app mientras desarrollas, sigue los pasos que se indican a continuación para registrar el dispositivo de prueba de manera programática.

  1. Llama a requestConsentInfoUpdate().
  2. Revisa el resultado del registro para ver un mensaje similar al siguiente, que muestra tu ID de dispositivo y cómo agregarlo como un dispositivo de prueba:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Copia el ID de tu dispositivo de prueba en el portapapeles.

  4. Modifica tu código para llamar a ConsentDebugSettings.Builder().addTestDeviceHashedId() y pasar una lista de los IDs de tus dispositivos de prueba.

Java

ConsentDebugSettings debugSettings = new ConsentDebugSettings.Builder(this)
    .addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
    .build();

ConsentRequestParameters params = new ConsentRequestParameters
    .Builder()
    .setConsentDebugSettings(debugSettings)
    .build();

consentInformation = UserMessagingPlatform.getConsentInformation(this);
// Include the ConsentRequestParameters in your consent request.
consentInformation.requestConsentInfoUpdate(
    this,
    params,
    ...
);

Kotlin

val debugSettings = ConsentDebugSettings.Builder(this)
    .addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
    .build()

val params = ConsentRequestParameters
    .Builder()
    .setConsentDebugSettings(debugSettings)
    .build()

consentInformation = UserMessagingPlatform.getConsentInformation(this)
// Include the ConsentRequestParameters in your consent request.
consentInformation.requestConsentInfoUpdate(
    this,
    params,
    ...
)

Cómo forzar una geografía

El SDK de UMP proporciona una forma de probar el comportamiento de tu app como si el dispositivo se encontrara en el EEE o el Reino Unido mediante the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builder. Ten en cuenta que la configuración de depuración solo funciona en dispositivos de prueba.

Java

ConsentDebugSettings debugSettings = new ConsentDebugSettings.Builder(this)
    .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
    .addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
    .build();

ConsentRequestParameters params = new ConsentRequestParameters
    .Builder()
    .setConsentDebugSettings(debugSettings)
    .build();

consentInformation = UserMessagingPlatform.getConsentInformation(this);
// Include the ConsentRequestParameters in your consent request.
consentInformation.requestConsentInfoUpdate(
    this,
    params,
    ...
);

Kotlin

val debugSettings = ConsentDebugSettings.Builder(this)
    .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
    .addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
    .build()

val params = ConsentRequestParameters
    .Builder()
    .setConsentDebugSettings(debugSettings)
    .build()

consentInformation = UserMessagingPlatform.getConsentInformation(this)
// Include the ConsentRequestParameters in your consent request.
consentInformation.requestConsentInfoUpdate(
    this,
    params,
    ...
)

Cuando pruebes tu app con el SDK de UMP, tal vez te resulte útil restablecer el estado del SDK para simular la primera experiencia de instalación de un usuario. El SDK proporciona el método reset() para hacerlo.

Java

consentInformation.reset();

Kotlin

consentInformation.reset()