Memulai

Berdasarkan Kebijakan Izin Pengguna Uni Eropa Google, Anda harus membuat pengungkapan tertentu untuk pengguna di Wilayah Ekonomi Eropa (EEA) bersama dengan Inggris Raya dan mendapatkan izin mereka untuk menggunakan cookie atau penyimpanan lokal lainnya, jika diwajibkan secara hukum, dan untuk menggunakan data pribadi (seperti ID iklan) untuk menayangkan iklan. Kebijakan ini mencerminkan persyaratan dalam ePrivacy Directive dan General Data Protection Regulation (GDPR) Uni Eropa.

Untuk mendukung penayang dalam memenuhi kewajibannya berdasarkan kebijakan ini, Google menawarkan User Messaging Platform (UMP) SDK. UMP SDK telah diperbarui untuk mendukung standar IAB terbaru. Semua konfigurasi ini kini dapat ditangani dengan mudah di AdMob privasi & pesan.

Prasyarat

  • API Android level 21 atau yang lebih tinggi

Membuat jenis pesan

Buat pesan pengguna dengan salah satu jenis pesan pengguna yang tersedia di tab Privasi & pesan di akun AdMob Anda. UMP SDK mencoba menampilkan pesan pengguna yang dibuat dari AdMob ID Aplikasi yang ditetapkan dalam project Anda. Jika tidak ada pesan yang dikonfigurasi untuk aplikasi Anda, SDK akan menampilkan error.

Untuk mengetahui detail selengkapnya, lihat Tentang privasi dan pesan.

Menginstal dengan Gradle

Tambahkan dependensi untuk Google User Messaging Platform SDK ke file Gradle level aplikasi modul, biasanya app/build.gradle:

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

Setelah melakukan perubahan pada build.gradle aplikasi Anda, pastikan untuk menyinkronkan project Anda dengan file Gradle.

Anda harus meminta pembaruan informasi izin pengguna setiap kali aplikasi diluncurkan, menggunakan requestConsentInfoUpdate(). Langkah ini menentukan apakah pengguna Anda perlu memberikan izin jika mereka belum melakukannya, atau apakah izin mereka sudah tidak berlaku.

Berikut adalah contoh cara memeriksa status dari MainActivity dalam metode 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}")
        })
  }
}

Muat dan tampilkan formulir izin jika diperlukan

Penting: API berikut kompatibel dengan UMP SDK versi 2.1.0 atau yang lebih tinggi.

Setelah Anda menerima status izin terbaru, panggilloadAndShowConsentFormIfRequired() di classConsentForm untuk memuat formulir izin. Jika status izin diwajibkan, SDK akan memuat formulir dan segera menampilkannya dari activityyang disediakan. Formulir callback akan dipanggil setelah formulir ditutup. Jika izin tidak diperlukan, callback akan segera dipanggil .

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

Jika Anda perlu melakukan tindakan apa pun setelah pengguna menentukan pilihan atau menutup formulir, tempatkan logika tersebut dalam callback untuk formulir Anda.

Permintaan iklan

Sebelum meminta iklan di aplikasi, periksa apakah Anda telah mendapatkan izin dari pengguna menggunakan canRequestAds(). Ada dua tempat yang harus diperiksa saat mengumpulkan izin:

  1. Setelah izin dikumpulkan di sesi saat ini.
  2. Segera setelah Anda menelepon requestConsentInfoUpdate(). Kemungkinan izin telah diperoleh di sesi sebelumnya. Sebagai praktik terbaik latensi, sebaiknya jangan menunggu callback selesai sehingga Anda dapat mulai memuat iklan sesegera mungkin setelah aplikasi diluncurkan.

Jika terjadi error selama proses pengumpulan izin, sebaiknya Anda tetap mencoba meminta iklan. UMP SDK menggunakan status izin dari sesi sebelumnya.

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

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

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

Opsi privasi

Beberapa formulir izin mewajibkan pengguna untuk mengubah izinnya kapan saja. Patuhi langkah-langkah berikut untuk menerapkan tombol opsi privasi jika diperlukan.

Untuk melakukan hal ini:

  1. Implementasikan elemen UI, seperti tombol di halaman setelan aplikasi, yang dapat memicu formulir opsi privasi.
  2. Setelah loadAndShowConsentFormIfRequired() selesai, periksa privacyOptionsRequirementStatus() untuk menentukan apakah akan menampilkan elemen UI yang dapat menampilkan formulir opsi privasi.
  3. Saat pengguna berinteraksi dengan elemen UI, panggil showPrivacyOptionsForm() untuk menampilkan formulir tersebut sehingga pengguna dapat memperbarui opsi privasi kapan saja.

Contoh berikut menunjukkan cara menampilkan formulir opsi privasi dari 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)
}

Pengujian

Jika Anda ingin menguji integrasi di aplikasi saat mengembangkan, ikuti langkah-langkah berikut untuk mendaftarkan perangkat pengujian secara terprogram. Pastikan Anda menghapus kode yang menetapkan ID perangkat pengujian ini sebelum merilis aplikasi.

  1. Panggil requestConsentInfoUpdate().
  2. Periksa output log untuk melihat pesan yang mirip dengan contoh berikut, yang menampilkan ID perangkat Anda dan cara menambahkannya sebagai perangkat pengujian:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Salin ID perangkat pengujian Anda ke papan klip.

  4. Ubah kode Anda untuk memanggil ConsentDebugSettings.Builder().addTestDeviceHashedId() dan meneruskan daftar ID perangkat pengujian Anda.

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

Paksa geografi

UMP SDK menyediakan cara untuk menguji perilaku aplikasi Anda seolah-olah perangkat tersebut berada di EEA atau Inggris Raya menggunakan the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builder. Perhatikan bahwa setelan debug hanya berfungsi pada perangkat pengujian.

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

Dalam menguji aplikasi dengan UMP SDK, mereset status SDK mungkin dapat membantu Anda menyimulasikan pengalaman penginstalan pertama pengguna. SDK menyediakan metode reset() untuk melakukannya.

Java

consentInformation.reset();

Kotlin

consentInformation.reset()

Contoh di GitHub

Contoh integrasi UMP SDK: Java | Kotlin