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, ove richiesto dalla legge, nonché di utilizzare 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 User Messaging Platform (UMP). L'SDK UMP è stato aggiornato per supportare i più recenti standard IAB. Ora tutte queste configurazioni possono essere gestite comodamente nella sezione AdMob Privacy e messaggi.
Prerequisiti
- Completa la Guida introduttiva
- Livello API Android 21 o superiore
- Se ti occupi dei requisiti relativi al GDPR, leggi In che modo i requisiti IAB influiscono sui messaggi per il consenso dell'UE
Crea un tipo di messaggio
Crea messaggi per gli utenti con uno dei tipi di messaggi per gli utenti disponibili nella scheda Privacy e messaggi del tuo account AdMob . L'SDK UMP tenta di visualizzare un messaggio utente creato dall' AdMob ID applicazione impostato nel progetto. Se non viene 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, di solito app/build.gradle
:
dependencies {
implementation("com.google.android.ump:user-messaging-platform:2.2.0")
}
Dopo aver apportato le modifiche a build.gradle
dell'app, assicurati di sincronizzare il
progetto con i file Gradle.
Aggiungi l'ID applicazione
Puoi trovare il tuo ID applicazione nell'UI di AdMob.
Aggiungi l'ID a
AndroidManifest.xml
con il seguente snippet di codice:
<manifest>
<application>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
Richiesta di informazioni sul consenso
Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente a ogni avvio dell'app utilizzando requestConsentInfoUpdate()
. In questo modo viene stabilito se l'utente deve fornire il consenso, se non l'ha già fatto o se è 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, "${requestConsentError.errorCode}: ${requestConsentError.message}")
})
}
}
Carica e mostra un modulo di consenso, se necessario
Dopo aver ricevuto lo stato del consenso più aggiornato, chiama
loadAndShowConsentFormIfRequired()
il corso
ConsentForm
per caricare un modulo di consenso. Se lo
stato del consenso è obbligatorio, l'SDK carica un modulo e lo presenta immediatamente
dal activityfornito. Il campo callback
viene richiamato dopo che il modulo è stato ignorato. Se il consenso non è richiesto, il callback
viene richiamato 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 ->
if (loadAndShowError != null) {
// Consent gathering failed.
Log.w(TAG, "${loadAndShowError.errorCode}: ${loadAndShowError.message}")
}
// Consent has been gathered.
}
)
},
ConsentInformation.OnConsentInfoUpdateFailureListener {
requestConsentError ->
// Consent gathering failed.
Log.w(TAG, "${requestConsentError.errorCode}: ${requestConsentError.message}")
})
}
}
Se devi eseguire un'azione dopo che l'utente ha scelto o ignorato il modulo, inserisci tale logica nel callback modulo.
Richiedi annunci
Prima di richiedere annunci nella tua app, verifica di aver ottenuto il consenso
da parte dell'utente che utilizza canRequestAds()
. Ci sono due
punti da controllare durante la raccolta del consenso:
- Una volta raccolto il consenso nella sessione corrente,
- Subito dopo aver chiamato
requestConsentInfoUpdate()
. È possibile che il consenso sia stato ottenuto nella sessione precedente. Come best practice sulla latenza, ti consigliamo di non attendere il completamento del callback per poter iniziare a caricare gli annunci il prima possibile dopo il lancio dell'app.
Se si verifica un errore durante la procedura di raccolta del consenso, dovresti comunque tentare di 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;
}
new Thread(
() -> {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this, initializationStatus -> {});
runOnUiThread(
() -> {
// TODO: Request an ad.
// InterstitialAd.load(...);
});
})
.start();
}
}
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 ->
if (loadAndShowError != null) {
// Consent gathering failed.
Log.w(TAG, "${loadAndShowError.errorCode}: ${loadAndShowError.message}")
}
// Consent has been gathered.
if (consentInformation.canRequestAds()) {
initializeMobileAdsSdk()
}
}
)
},
ConsentInformation.OnConsentInfoUpdateFailureListener {
requestConsentError ->
// Consent gathering failed.
Log.w(TAG, "${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
}
val backgroundScope = CoroutineScope(Dispatchers.IO)
backgroundScope.launch {
// Initialize the Google Mobile Ads SDK on a background thread.
MobileAds.initialize(this@MainActivity) {}
// TODO: Request an ad.
// InterstitialAd.load(...)
}
}
}
Opzioni di privacy
Alcuni moduli di consenso richiedono all'utente di modificare il proprio consenso in qualsiasi momento. Segui i passaggi riportati di seguito per implementare un pulsante delle opzioni sulla privacy, se necessario.
A questo scopo:
- Implementare un elemento UI, ad esempio un pulsante nella pagina delle impostazioni dell'app, che può attivare un modulo per le opzioni sulla privacy.
- Una volta
loadAndShowConsentFormIfRequired()
completato, controllaprivacyOptionsRequirementStatus()
per stabilire se visualizzare l'elemento UI che può presentare il modulo delle opzioni di privacy. - Quando un utente interagisce con l'elemento UI, chiama
showPrivacyOptionsForm()
per mostrare il modulo in modo che l'utente possa aggiornare le proprie opzioni di privacy in qualsiasi momento.
L'esempio seguente mostra come presentare il modulo per le opzioni sulla 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 in corso
Se vuoi testare l'integrazione nella tua app durante lo sviluppo, segui questi passaggi per registrare il dispositivo di test in modo programmatico. Assicurati di rimuovere il codice che imposta questi ID dispositivo di test prima di rilasciare l'app.
- Chiama il numero
requestConsentInfoUpdate()
. Controlla nell'output del log un messaggio simile all'esempio seguente, che mostra l'ID dispositivo e come aggiungerlo come dispositivo di test:
Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
Copia l'ID del dispositivo di test negli appunti.
Modifica il codice per chiamare
ConsentDebugSettings.Builder().addTestDeviceHashedId()
e passare un elenco dei tuoi ID dispositivo di test.
Forzare un'area geografica
L'SDK UMP consente di testare il comportamento della tua app come se il dispositivo si trovasse nello Spazio economico europeo 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,
...
)
Reimposta stato del consenso
Durante il test della tua app con l'SDK UMP, potrebbe essere utile reimpostare
lo stato dell'SDK in modo da simulare l'esperienza della 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