Rozpocznij

Zgodnie z polityką Google w zakresie zgody użytkownika z UE musisz udzielać odpowiednich informacji użytkownikom z Europejskiego Obszaru Gospodarczego (EOG) i Wielkiej Brytanii oraz uzyskiwać ich zgodę na stosowanie plików cookie lub innych środków do lokalnego przechowywania danych, jeśli jest to wymagane prawnie, oraz na wykorzystywanie danych osobowych (takich jak AdID) do wyświetlania reklam. Polityka ta odzwierciedla wymagania UE zawarte w dyrektywie o prywatności i łączności elektronicznej oraz w Ogólnym rozporządzeniu o ochronie danych (RODO).

Aby pomóc wydawcom w wypełnieniu obowiązków, jakie nakłada na nich ta polityka, Google oferuje pakiet SDK User Messaging Platform (UMP). Pakiet UMP SDK został zaktualizowany, aby był zgodny z najnowszymi standardami IAB. Wszystkimi tymi konfiguracjami można teraz wygodnie zarządzać Interactive Media Ads na stronie „Prywatność i wyświetlanie wiadomości”.

Prawidłową implementację IMA z pakietem UMP SDK możesz zobaczyć w przykładowej aplikacji UMP.

Wymagania wstępne

  • Android API na poziomie 21 lub wyższym

Tworzenie typu wiadomości

Utwórz wiadomości dla użytkowników, używając jednego z dostępnych typów wiadomości na karcie Prywatność i wyświetlanie wiadomości na koncie Ad Managera . Pakiet UMP SDK próbuje wyświetlić wiadomość dla użytkownika utworzoną na podstawie Interactive Media Ads identyfikatora aplikacji ustawionego w Twoim projekcie. Jeśli dla aplikacji nie jest skonfigurowany żaden komunikat, pakiet SDK zwróci błąd.

Więcej informacji znajdziesz w artykule Prywatność i wyświetlanie wiadomości

Instalowanie za pomocą Gradle

Dodaj zależność z pakietem SDK User Messaging Platform od Google do pliku Gradle na poziomie aplikacji modułu (zwykle app/build.gradle):

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

Po wprowadzeniu zmian w projekcie build.gradle aplikacji zsynchronizuj swój projekt z plikami Gradle.

Należy prosić o aktualizację informacji o zgodzie użytkownika przy każdym uruchomieniu aplikacji za pomocą narzędzia requestConsentInfoUpdate(). Określa, czy użytkownik musi wyrazić zgodę, jeśli jeszcze tego nie zrobił, czy też wygasła.

Oto przykład, jak sprawdzić stan z poziomu obiektu MainActivity w metodzie 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}")
        })
  }
}

W razie potrzeby wczytaj i wyświetl formularz zgody

Po uzyskaniu najbardziej aktualnego stanu zgody wywołajloadAndShowConsentFormIfRequired() wConsentForm klasie, aby wczytać formularz zgody. Jeśli stan zgody użytkownika jest wymagany, pakiet SDK wczytuje formularz i natychmiast wyświetla go z przesłanego activity. Po zamknięciu formularza callback jest wywoływany . Jeśli zgoda nie jest wymagana, callback wywoływane natychmiast.

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

Jeśli musisz wykonać jakieś działania po dokonaniu wyboru lub zamknięciu formularza przez użytkownika, umieść tę logikę w callbackformularza.

Wyślij żądanie

Zanim wyślesz prośbę o reklamy w aplikacji, sprawdź, czy masz zgodę użytkownika za pomocą canRequestAds(). Uzyskując zgodę, można to sprawdzić w dwóch miejscach:

  1. Po uzyskaniu zgody użytkownika podczas bieżącej sesji.
  2. Zaraz po nawiązaniu połączenia z firmą requestConsentInfoUpdate(). Możliwe, że w poprzedniej sesji użytkownik wyraził zgodę. Zalecamy, aby nie czekać na zakończenie wywołania zwrotnego i w razie potrzeby zacząć wczytywać reklamy jak najszybciej po uruchomieniu aplikacji.

Jeśli podczas uzyskiwania zgody użytkowników wystąpi błąd, nadal próbuj wysyłać żądania reklam. Pakiet UMP SDK używa stanu zgody z poprzedniej sesji.

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.
              if (consentInformation.canRequestAds()) {
                initializeImaSdk();
              }
            }
          );
        },
        (OnConsentInfoUpdateFailureListener) requestConsentError -> {
          // Consent gathering failed.
          Log.w(TAG, String.format("%s: %s",
              requestConsentError.getErrorCode(),
              requestConsentError.getMessage()));
        });
    
    // Check if you can initialize the IMA SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if (consentInformation.canRequestAds()) {
      initializeImaSdk();
    }
  }
  
  private void initializeImaSdk() {
    sdkFactory = ImaSdkFactory.getInstance();

    // TODO: Initialize IMA by creating an AdDisplayContainer, an AdsLoader,
    // and making an ad request.
  }
}

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.
              if (consentInformation.canRequestAds()) {
                initializeImaSdk()
              }
            }
          )
        },
        ConsentInformation.OnConsentInfoUpdateFailureListener {
          requestConsentError ->
          // Consent gathering failed.
          Log.w(TAG, "${requestConsentError.errorCode}: ${requestConsentError.message}")
        })
    
    // Check if you can initialize the IMA SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if (consentInformation.canRequestAds()) {
      initializeImaSdk()
    }
  }
  
  private void initializeImaSdk() {
    sdkFactory = ImaSdkFactory.getInstance()

    // TODO: Initialize IMA by creating an AdDisplayContainer, an AdsLoader,
    // and making an ad request.
  }
}

Opcje prywatności

Niektóre formularze zgody wymagają od użytkownika zmiany zgody w dowolnym momencie. Aby w razie potrzeby zaimplementować przycisk opcji prywatności, wykonaj te czynności.

W tym celu:

  1. Zaimplementuj element interfejsu, np. przycisk na stronie ustawień aplikacji, który będzie uruchamiać formularz opcji prywatności.
  2. Po loadAndShowConsentFormIfRequired() zakończenia sprawdźprivacyOptionsRequirementStatus() , czy wyświetlić element interfejsu, który może wyświetlić formularz opcji prywatności.
  3. Gdy użytkownik wejdzie w interakcję z elementem interfejsu, wywołajshowPrivacyOptionsForm() , aby wyświetlić formularz. Dzięki temu w każdej chwili będzie mógł zaktualizować swoje opcje prywatności.

Poniższy przykład pokazuje, jak wyświetlić formularz opcji prywatności z poziomu 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)
}

Testuję

Jeśli chcesz przetestować integrację ze swoją aplikacją w trakcie jej programowania, wykonaj te czynności, aby automatycznie zarejestrować urządzenie testowe. Pamiętaj, by przed opublikowaniem aplikacji usunąć kod, który ustawia te identyfikatory urządzeń testowych.

  1. Zadzwoń pod numer requestConsentInfoUpdate().
  2. Sprawdź w logu, czy w danych wyjściowych znajduje się komunikat podobny do tego poniżej. Zawiera on identyfikator urządzenia i sposób dodawania go jako urządzenia testowego:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Skopiuj identyfikator urządzenia testowego do schowka.

  4. Zmodyfikuj kod, aby wywoływać ConsentDebugSettings.Builder().addTestDeviceHashedId() i przekazywać listę identyfikatorów urządzeń testowych.

Wymuś użycie lokalizacji geograficznej

Pakiet UMP SDK umożliwia przetestowanie działania aplikacji w taki sposób, jakby urządzenie znajdowało się w Europejskim Obszarze Gospodarczym lub Wielkiej Brytanii za pomocą usługi the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builder. Pamiętaj, że ustawienia debugowania działają tylko na urządzeniach testowych.

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

Podczas testowania aplikacji za pomocą pakietu SDK UMP warto zresetować stan pakietu SDK, aby przeprowadzić symulację pierwszej instalacji aplikacji u użytkownika. Pakiet SDK udostępnia metodę reset() .

Java

consentInformation.reset();

Kotlin

consentInformation.reset()