Inizia

Secondo le Norme relative al consenso degli utenti dell'UE di Google, è obbligatorio informare gli utenti nello Spazio economico europeo (SEE) e nel Regno Unito e ricevere il loro consenso per l'utilizzo dei cookie o di altri tipi di archiviazione locale, laddove richiesto dalla legge, e per l'utilizzo dei dati personali (ad esempio l'ID pubblicità) per la pubblicazione di annunci. Queste norme riflettono i requisiti della direttiva e-Privacy e del Regolamento generale sulla protezione dei dati (GDPR) dell'UE.

Per supportare i publisher nell'adempimento degli obblighi previsti da queste norme, Google offre l'SDK UMP (User Messaging Platform). L'SDK UMP è stato aggiornato per supportare i più recenti standard IAB. Tutte queste configurazioni ora possono essere comodamente gestite in AdMob privacy e messaggi.

Prerequisiti

  • Livello API Android 21 o successivo

Crea un tipo di messaggio

Crea i messaggi per gli utenti con uno dei tipi di messaggi per gli utenti disponibili nella scheda Privacy e messaggi del tuo AdMob account. L'SDK UMP tenta di visualizzare un messaggio utente creato dall' AdMob ID applicazione impostato nel progetto. Se non è configurato alcun messaggio per la tua applicazione, l'SDK restituisce un errore.

Per maggiori dettagli, consulta Informazioni su privacy e messaggi.

Installa con Gradle

Aggiungi la dipendenza per l'SDK Google User Messaging Platform al file Gradle a livello di app del modulo, normalmente app/build.gradle:

dependencies {
  implementation("com.google.android.ump:user-messaging-platform:2.1.0")
}

Dopo aver apportato le modifiche a build.gradle dell'app, assicurati di sincronizzare il progetto con i file Gradle.

Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente a ogni lancio dell'app, utilizzando requestConsentInfoUpdate(). Questo determina se l'utente deve dare il consenso nel caso in cui non l'abbia già fatto o se il consenso è scaduto.

Ecco un esempio di come controllare lo stato da MainActivity nel metodo 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);

    // Create a ConsentRequestParameters object.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .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)

    // Create a ConsentRequestParameters object.
    val params = ConsentRequestParameters
        .Builder()
        .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()))
        })
  }
}

Carica e mostra un modulo di consenso, se necessario

Importante: le API seguenti sono compatibili con l'SDK UMP versione 2.1.0 o successive.

Dopo aver ricevuto lo stato del consenso più aggiornato, chiama loadAndShowConsentFormIfRequired() il ConsentForm corso per caricare un modulo di consenso. Se lo stato del consenso è obbligatorio, l'SDK carica un modulo e lo presenta immediatamente dal activityspecificato. Il callback viene richiamato dopo che il modulo viene ignorato. Se il consenso non è richiesto, il callback viene chiamato immediatamente.

Java

public class MainActivity extends AppCompatActivity {
  private ConsentInformation consentInformation;

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

    // Create a ConsentRequestParameters object.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .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)

    // Create a ConsentRequestParameters object.
    val params = ConsentRequestParameters
        .Builder()
        .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()))
        })
  }
}

Se devi eseguire azioni dopo che l'utente ha scelto o ignorato il modulo, inserisci la logica corrispondente nel callbackmodulo.

Richiedi annunci

Prima di richiedere annunci nella tua app, verifica di aver ottenuto il consenso da parte dell'utente utilizzando canRequestAds(). Esistono due punti da controllare durante la raccolta del consenso:

  1. Una volta ottenuto il consenso nella sessione corrente.
  2. Subito dopo aver chiamato requestConsentInfoUpdate(). È possibile che il consenso sia stato ottenuto nella sessione precedente. Come best practice in materia di latenza, ti consigliamo di non attendere il completamento del callback in modo da poter iniziare a caricare gli annunci il prima possibile dopo l'avvio dell'app.

Se si verifica un errore durante la procedura di raccolta del consenso, devi comunque provare a richiedere gli annunci. L'SDK UMP utilizza lo stato del consenso della sessione precedente.

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);

    // Create a ConsentRequestParameters object.
    ConsentRequestParameters params = new ConsentRequestParameters
        .Builder()
        .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)

    // Create a ConsentRequestParameters object.
    val params = ConsentRequestParameters
        .Builder()
        .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.getAndSet(true)) {
      return
    }

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

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

Opzioni relative alla privacy

Alcuni moduli di consenso richiedono all'utente di modificare il consenso in qualsiasi momento. Rispetta i seguenti passaggi per implementare un pulsante Opzioni di privacy, se necessario.

A questo scopo:

  1. Implementa un elemento UI, ad esempio un pulsante nella pagina delle impostazioni dell'app, che può attivare un modulo delle opzioni di privacy.
  2. Una volta loadAndShowConsentFormIfRequired() completato, controlla privacyOptionsRequirementStatus() per determinare se visualizzare l'elemento UI che può presentare il modulo delle opzioni di privacy.
  3. Quando un utente interagisce con il tuo elemento UI, chiamashowPrivacyOptionsForm() per mostrare il modulo in modo che l'utente possa aggiornare le opzioni sulla privacy in qualsiasi momento.

L'esempio seguente mostra come presentare il modulo delle opzioni di privacy da un MenuItem.

Java

private final ConsentInformation consentInformation;

// Show a privacy options button if required.
public boolean isPrivacyOptionsRequired() {
  return consentInformation.getPrivacyOptionsRequirementStatus()
      == PrivacyOptionsRequirementStatus.REQUIRED;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
  // ...

  consentInformation = UserMessagingPlatform.getConsentInformation(this);
  consentInformation.requestConsentInfoUpdate(
      this,
      params,
      (OnConsentInfoUpdateSuccessListener) () -> {
        UserMessagingPlatform.loadAndShowConsentFormIfRequired(
          this,
          (OnConsentFormDismissedListener) loadAndShowError -> {
            // ...

            // Consent has been gathered.

            if (isPrivacyOptionsRequired()) {
              // Regenerate the options menu to include a privacy setting.
              invalidateOptionsMenu();
            }
          }
        )
      }
      // ...
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.action_menu, menu);
  MenuItem moreMenu = menu.findItem(R.id.action_more);
  moreMenu.setVisible(isPrivacyOptionsRequired());
  return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  // ...

  popup.setOnMenuItemClickListener(
      popupMenuItem -> {
        if (popupMenuItem.getItemId() == R.id.privacy_settings) {
          // Present the privacy options form when a user interacts with
          // the privacy settings button.
          UserMessagingPlatform.showPrivacyOptionsForm(
              this,
              formError -> {
                if (formError != null) {
                  // Handle the error.
                }
              }
          );
          return true;
        }
        return false;
      });
  return super.onOptionsItemSelected(item);
}

Kotlin

private val consentInformation: ConsentInformation =
  UserMessagingPlatform.getConsentInformation(context)

// Show a privacy options button if required.
val isPrivacyOptionsRequired: Boolean
  get() =
    consentInformation.privacyOptionsRequirementStatus ==
      ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED

override fun onCreate(savedInstanceState: Bundle?) {
  ...
  consentInformation = UserMessagingPlatform.getConsentInformation(this)
  consentInformation.requestConsentInfoUpdate(
      this,
      params,
      ConsentInformation.OnConsentInfoUpdateSuccessListener {
        UserMessagingPlatform.loadAndShowConsentFormIfRequired(
          this@MainActivity,
          ConsentForm.OnConsentFormDismissedListener {
            // ...

            // Consent has been gathered.

            if (isPrivacyOptionsRequired) {
              // Regenerate the options menu to include a privacy setting.
              invalidateOptionsMenu();
            }
          }
        )
      }
      // ...
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
  menuInflater.inflate(R.menu.action_menu, menu)
  menu?.findItem(R.id.action_more)?.apply {
    isVisible = isPrivacyOptionsRequired
  }
  return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
  // ...

  popup.setOnMenuItemClickListener { popupMenuItem ->
    when (popupMenuItem.itemId) {
      R.id.privacy_settings -> {
        // Present the privacy options form when a user interacts with
        // the privacy settings button.
        UserMessagingPlatform.showPrivacyOptionsForm(this) { formError ->
          formError?.let {
            // Handle the error.
          }
        }
        true
      }
      else -> false
    }
  }
  return super.onOptionsItemSelected(item)
}

Test

Se vuoi testare l'integrazione nella tua app durante lo sviluppo, segui i passaggi riportati di seguito per registrare in modo programmatico il dispositivo di test.

  1. Chiama il numero requestConsentInfoUpdate().
  2. Controlla se nell'output del log è presente un messaggio simile a quello riportato di seguito, che mostra l'ID del tuo dispositivo e come aggiungerlo come dispositivo di test:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Copia l'ID dispositivo di test negli appunti.

  4. Modifica il codice per chiamare ConsentDebugSettings.Builder().addTestDeviceHashedId() e trasmettere un elenco dei tuoi ID dispositivo di test.

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,
    ...
)

Forzare un'area geografica

L'SDK UMP ti consente di testare il comportamento della tua app come se il dispositivo si trovasse nel SEE o nel Regno Unito utilizzando the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builder. Tieni presente che le impostazioni di debug funzionano solo sui dispositivi di test.

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,
    ...
)

Durante il test della tua app con l'SDK UMP, potrebbe essere utile reimpostare lo stato dell'SDK in modo da simulare la prima installazione di un utente. L'SDK fornisce il reset() metodo per farlo.

Java

consentInformation.reset();

Kotlin

consentInformation.reset()

Esempi su GitHub

Esempi di integrazione dell'SDK UMP: Java | Kotlin