Bắt đầu

Theo Chính sách về sự đồng ý của người dùng ở Liên minh Châu Âu của Google, bạn phải đưa ra một số thông tin công bố nhất định cho người dùng ở Khu vực kinh tế Châu Âu (EEA) cùng với Vương quốc Anh, đồng thời có được sự đồng ý của họ để sử dụng cookie hoặc các phương pháp lưu trữ cục bộ khác (khi pháp luật yêu cầu) và để sử dụng dữ liệu cá nhân (chẳng hạn như mã nhận dạng cho quảng cáo (AdID)) để phân phát quảng cáo. Chính sách này thể hiện các yêu cầu của Chỉ thị về quyền riêng tư và truyền thông điện tử của Liên minh Châu Âu cũng như Quy định chung về việc bảo vệ dữ liệu (GDPR).

Để giúp các nhà xuất bản đáp ứng các nghĩa vụ của họ theo chính sách này, Google cung cấp SDK Nền tảng thông báo cho người dùng (UMP). UMP SDK đã được cập nhật để hỗ trợ các tiêu chuẩn mới nhất của IAB. Giờ đây, bạn có thể xử lý tất cả các cấu hình này một cách thuận tiện trong phần AdMob quyền riêng tư và thông báo.

Điều kiện tiên quyết

  • API Android cấp 21 trở lên

Tạo một loại thông báo

Tạo thông báo cho người dùng bằng một trong các các loại thông báo hiện có cho người dùng trong thẻ Quyền riêng tư và thông báo của tài khoản AdMob . SDK UMP cố gắng hiển thị một thông báo cho người dùng được tạo từ AdMob Mã ứng dụng được đặt trong dự án của bạn. Nếu không có thông báo nào được định cấu hình cho ứng dụng, thì SDK sẽ trả về lỗi.

Để biết thêm thông tin, hãy xem bài viết Giới thiệu về quyền riêng tư và thông báo.

Cài đặt bằng Gradle

Thêm phần phụ thuộc cho SDK Nền tảng thông báo cho người dùng của Google vào tệp Gradle ở cấp ứng dụng trong mô-đun của bạn, thường là app/build.gradle:

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

Sau khi thay đổi build.gradle của ứng dụng, hãy nhớ đồng bộ hoá dự án của bạn với các tệp Gradle.

Bạn nên yêu cầu cập nhật thông tin về sự đồng ý của người dùng mỗi khi khởi chạy ứng dụng bằng cách sử dụng requestConsentInfoUpdate(). Điều này xác định liệu người dùng có cần đưa ra sự đồng ý hay không (nếu họ chưa làm vậy) hay nếu trạng thái đồng ý của họ đã hết hạn.

Dưới đây là ví dụ về cách kiểm tra trạng thái từ MainActivity trong phương thức 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()))
        })
  }
}

Tải và hiển thị biểu mẫu lấy sự đồng ý (nếu cần)

Quan trọng: Các API sau đây tương thích với SDK Nền tảng thông báo cho người dùng (UMP) phiên bản 2.1.0 trở lên.

Sau khi bạn nhận được trạng thái đồng ý mới nhất, hãy gọi loadAndShowConsentFormIfRequired() trên lớp ConsentForm để tải biểu mẫu đồng ý. Nếu trạng thái đồng ý là bắt buộc, SDK sẽ tải một biểu mẫu và ngay lập tức hiển thị biểu mẫu đó từ activityđược cung cấp. callback sẽ được gọi sau khi biểu mẫu bị loại bỏ. Nếu không cần có sự đồng ý, thì callback sẽ được gọi ngay lập tức.

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

Nếu bạn cần thực hiện bất kỳ hành động nào sau khi người dùng đã đưa ra lựa chọn hoặc đóng biểu mẫu, hãy đặt logic đó vào callbackcho biểu mẫu của bạn.

Yêu cầu quảng cáo

Trước khi yêu cầu quảng cáo trong ứng dụng của bạn, hãy kiểm tra xem bạn có được người dùng đồng ý bằng cách sử dụng canRequestAds()hay không. Có 2 nơi để kiểm tra trong quá trình thu thập sự đồng ý:

  1. Sau khi có được sự đồng ý trong phiên hiện tại.
  2. Ngay sau khi bạn gọi requestConsentInfoUpdate(). Có thể bạn đã nhận được sự đồng ý trong phiên trước đó. Một phương pháp hay nhất về độ trễ là bạn không nên đợi lệnh gọi lại hoàn tất để có thể bắt đầu tải quảng cáo ngay khi có thể sau khi ứng dụng khởi chạy.

Nếu xảy ra lỗi trong quá trình thu thập sự đồng ý, bạn vẫn nên tìm cách yêu cầu quảng cáo. SDK UMP sử dụng trạng thái đồng ý từ phiên trước.

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

Tuỳ chọn quyền riêng tư

Một số biểu mẫu đồng ý yêu cầu người dùng sửa đổi sự đồng ý của họ bất cứ lúc nào. Hãy làm theo các bước sau đây để triển khai nút tuỳ chọn quyền riêng tư nếu cần.

Để thực hiện điều này:

  1. Triển khai một thành phần trên giao diện người dùng, chẳng hạn như một nút trong trang cài đặt của ứng dụng, để có thể kích hoạt biểu mẫu các tuỳ chọn về quyền riêng tư.
  2. Sau khi loadAndShowConsentFormIfRequired() hoàn tất, hãy kiểm traprivacyOptionsRequirementStatus() để xác định xem có hiển thị thành phần trên giao diện người dùng có thể hiển thị biểu mẫu tuỳ chọn quyền riêng tư hay không.
  3. Khi người dùng tương tác với phần tử trên giao diện người dùng, hãy gọishowPrivacyOptionsForm() để hiển thị biểu mẫu và người dùng có thể cập nhật các tuỳ chọn quyền riêng tư của họ bất cứ lúc nào.

Ví dụ sau cho thấy cách trình bày biểu mẫu các tuỳ chọn quyền riêng tư từ 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)
}

Kiểm thử

Nếu bạn muốn kiểm thử tính năng tích hợp trong ứng dụng khi đang phát triển, hãy làm theo các bước sau để đăng ký thiết bị kiểm thử theo phương thức lập trình. Hãy nhớ xóa mã dùng để đặt các mã thiết bị thử nghiệm này trước khi bạn phát hành ứng dụng.

  1. Gọi requestConsentInfoUpdate().
  2. Kiểm tra đầu ra nhật ký để tìm một thông báo tương tự như ví dụ sau. Thông báo này cho biết mã thiết bị của bạn và cách thêm mã thiết bị đó làm thiết bị thử nghiệm:

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231") to set this as a debug device.
    
  3. Sao chép mã thiết bị thử nghiệm vào bảng nhớ tạm.

  4. Sửa đổi mã để gọi ConsentDebugSettings.Builder().addTestDeviceHashedId() và chuyển vào danh sách mã thiết bị thử nghiệm.

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

Chỉ định một vị trí địa lý

SDK UMP cung cấp một cách để kiểm thử hành vi của ứng dụng như thể thiết bị được đặt ở Khu vực kinh tế Châu Âu (EEA) hoặc Vương quốc Anh bằng cách sử dụng the setDebugGeography() method which takes a DebugGeography on ConsentDebugSettings.Builder. Xin lưu ý rằng chế độ gỡ lỗi chỉ hoạt động trên thiết bị thử nghiệm.

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

Khi kiểm thử ứng dụng bằng UMP SDK, bạn nên đặt lại trạng thái của SDK để có thể mô phỏng trải nghiệm cài đặt lần đầu của người dùng. SDK sẽ cung cấp phương thức reset() để thực hiện việc này.

Java

consentInformation.reset();

Kotlin

consentInformation.reset()

Ví dụ trên GitHub

Ví dụ về cách tích hợp SDK Nền tảng thông báo cho người dùng: Java | Kotlin