Erste Schritte

Gemäß der Google-Richtlinie zur Einwilligung der Nutzer in der EU müssen Sie Ihren Nutzern im Europäischen Wirtschaftsraum (EWR) sowie im Vereinigten Königreich bestimmte Informationen offenlegen und ihre Einwilligung zur Verwendung von Cookies oder anderen lokalen Speicherverfahren, sofern gesetzlich erforderlich, sowie zur Verwendung von personenbezogenen Daten wie der Werbe-ID für Anzeigen einholen. Die Richtlinie entspricht den Anforderungen der EU-Datenschutzrichtlinie für elektronische Kommunikation und der EU-Datenschutz-Grundverordnung (DSGVO).

Google bietet das User Messaging Platform (UMP) SDK, um Publisher bei der Umsetzung dieser Richtlinie zu unterstützen. Das UMP SDK wurde aktualisiert und unterstützt jetzt die neuesten IAB-Standards. All diese Konfigurationen können jetzt bequem unter AdMob „Datenschutz und Mitteilungen“ verwaltet werden.

Voraussetzungen

  • Android API-Level 21 oder höher

Mitteilungstyp erstellen

Sie können Nutzermitteilungen mit einem der verfügbaren Mitteilungstypen für Nutzer auf dem Tab Datenschutz und Mitteilungen in Ihrem AdMob erstellen. Das UMP SDK versucht, eine Nutzernachricht anzuzeigen, die mit der im Projekt festgelegten AdMob Anwendungs-ID erstellt wurde. Wenn für Ihre Anwendung keine Meldung konfiguriert ist, gibt das SDK einen Fehler zurück.

Weitere Informationen finden Sie unter Informationen zu Datenschutz und Mitteilungen.

Mit Gradle installieren

Fügen Sie die Abhängigkeit für das Google User Messaging Platform SDK in die Gradle-Datei Ihres Moduls auf App-Ebene ein (normalerweise app/build.gradle):

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

Nachdem du die Änderungen am build.gradle deiner App vorgenommen hast, musst du dein Projekt mit den Gradle-Dateien synchronisieren.

Sie sollten bei jedem Start der App mit requestConsentInfoUpdate()eine Aktualisierung der Einwilligungsinformationen des Nutzers anfordern. Damit wird bestimmt, ob der Nutzer seine Einwilligung geben muss, falls dies noch nicht geschehen ist oder die Einwilligung abgelaufen ist.

Im Folgenden finden Sie ein Beispiel dafür, wie Sie den Status von MainActivity in der Methode onCreate() prüfen.

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}")
        })
  }
}

Einwilligungsformular laden und bei Bedarf einblenden

Nachdem Sie den aktuellen Einwilligungsstatus erhalten haben, rufen SieloadAndShowConsentFormIfRequired() in der KlasseConsentForm auf, um ein Einwilligungsformular zu laden. Wenn der Einwilligungsstatus erforderlich ist, lädt das SDK ein Formular und zeigt es sofort aus dem bereitgestellten activityan. Die callback wird aufgerufen , nachdem das Formular geschlossen wurde. Ist keine Einwilligung erforderlich, wird der callback sofort aufgerufen .

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}")
        })
  }
}

Wenn du Aktionen ausführen musst, nachdem der Nutzer eine Auswahl getroffen oder das Formular geschlossen hat, platziere diese Logik in der callbackfür dein Formular.

Anzeigenanfrage senden

Bevor Sie Anzeigen in Ihrer App anfordern, prüfen Sie, ob Sie über canRequestAds()die Einwilligung des Nutzers eingeholt haben. Beim Einholen der Einwilligung müssen Sie zwei Stellen prüfen:

  1. Sobald in der aktuellen Sitzung die Einwilligung eingeholt wurde.
  2. Unmittelbar nach Ihrem Anruf bei requestConsentInfoUpdate() Möglicherweise wurde die Einwilligung bereits in der vorherigen Sitzung erteilt. Als Best Practice für die Latenz empfehlen wir, nicht auf den Abschluss des Callbacks zu warten, damit du nach dem Start deiner App so schnell wie möglich mit dem Laden von Anzeigen beginnen kannst.

Wenn beim Einholen der Einwilligung ein Fehler auftritt, sollten Sie trotzdem versuchen, Anzeigen anzufordern. Das UMP SDK verwendet den Einwilligungsstatus aus der vorherigen Sitzung.

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(...)
    }
  }
}

Datenschutzoptionen

Bei einigen Einwilligungsformularen muss der Nutzer seine Einwilligung jederzeit ändern. Führe bei Bedarf die folgenden Schritte aus, um eine Schaltfläche für Datenschutzoptionen zu implementieren.

Folgende Schritte sind hierzu nötig:

  1. Implementieren Sie ein UI-Element, z. B. eine Schaltfläche auf der Einstellungsseite Ihrer App, über das ein Formular mit Datenschutzoptionen ausgelöst werden kann.
  2. Sobald loadAndShowConsentFormIfRequired() abgeschlossen ist, prüfen SieprivacyOptionsRequirementStatus() , um zu bestimmen, ob das UI-Element angezeigt werden soll, über das das Formular für Datenschutzoptionen angezeigt werden kann.
  3. Wenn ein Nutzer mit Ihrem UI-Element interagiert, rufen SieshowPrivacyOptionsForm() auf, um das Formular aufzurufen, sodass der Nutzer seine Datenschutzoptionen jederzeit aktualisieren kann.

Das folgende Beispiel zeigt, wie das Formular für Datenschutzoptionen aus einem MenuItem dargestellt wird.

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

Testen

Wenn du die Integration in deine App während der Entwicklung testen möchtest, folge dieser Anleitung, um dein Testgerät programmatisch zu registrieren. Entferne den Code, mit dem diese Testgeräte-IDs festgelegt werden, bevor du deine App veröffentlichst.

  1. Rufen Sie uns unter requestConsentInfoUpdate()an.
  2. Suchen Sie in der Logausgabe nach einer Nachricht ähnlich der folgenden. Sie enthält Ihre Geräte-ID und wie Sie sie als Testgerät hinzufügen können:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Kopieren Sie die Testgeräte-ID in die Zwischenablage.

  4. Ändern Sie den Code so, dass aufgerufenConsentDebugSettings.Builder().addTestDeviceHashedId() und eine Liste Ihrer Testgeräte-IDs übergeben wird.

Geografie erzwingen

Mit dem UMP SDK können Sie das Verhalten Ihrer App testen, als würde sich das Gerät mithilfe von the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builderim EWR oder Vereinigten Königreich befinden. Die Debugging-Einstellungen funktionieren nur auf Testgeräten.

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

Wenn Sie Ihre App mit dem UMP SDK testen, kann es hilfreich sein, den Status des SDK zurückzusetzen, um die erste Installation eines Nutzers zu simulieren. Das SDK bietet dazu die Methode reset() .

Java

consentInformation.reset();

Kotlin

consentInformation.reset()

Beispiele auf GitHub

Beispiele für die UMP SDK-Integration: Java | Kotlin