开始使用

根据 Google《欧盟地区用户意见征求政策》,您必须向位于欧洲经济区 (EEA) 以及英国境内的用户披露相关信息;在法律有要求的情况下,必须征得他们的同意才能使用 Cookie 或其他本地存储方式;此外,您必须同意他们使用个人数据(例如 AdID)来投放广告。此政策反映了欧盟《电子隐私指令》和《一般数据保护条例》(GDPR) 的要求。

为了帮助发布商履行此政策规定的职责,Google 提供了 User Messaging Platform (UMP) SDK。UMP SDK 已更新,可支持最新的 IAB 标准。所有这些配置现在都可以在“隐私权和消息”中轻松处理。 AdMob

前提条件

  • Android API 级别 21 或更高级别(适用于 Android)

创建消息类型

创建用户消息时,您可以使用 可用的用户消息类型 (在 AdMob 账号的隐私权和消息标签页下)创建用户消息。UMP SDK 会尝试显示通过 AdMob 中设置的应用 ID 创建的用户消息。如果没有为您的应用配置消息,SDK 会返回错误。

如需了解详情,请参阅 隐私权和消息简介

安装 SDK

  1. 按照相应步骤安装 Google 移动广告 (GMA) C++ SDK。UMP C++ SDK 包含在 GMA C++ SDK 中。

  2. 请确保在项目中配置应用的 AdMob 应用 ID,然后再继续。

  3. 在代码中,通过调用 ConsentInfo::GetInstance() 来初始化 UMP SDK。

    • 在 Android 中,您需要传入 NDK 提供的 JNIEnvActivity。您只需在首次调用 GetInstance() 时执行此操作。
    • 或者,如果您已在应用中使用 Firebase C++ SDK,则可以在首次调用 GetInstance() 时传入 firebase::App
    #include "firebase/gma/ump.h"
    
    namespace ump = ::firebase::gma::ump;
    
    // Initialize using a firebase::App
    void InitializeUserMessagingPlatform(const firebase::App& app) {
      ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance(app);
    }
    
    // Initialize without a firebase::App
    #ifdef ANDROID
    void InitializeUserMessagingPlatform(JNIEnv* jni_env, jobject activity) {
      ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance(jni_env, activity);
    }
    #else  // non-Android
    void InitializeUserMessagingPlatform() {
      ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance();
    }
    #endif
    

ConsentInfo::GetInstance() 的后续调用均返回同一实例。

如果您使用完 UMP SDK,可以通过删除 ConsentInfo 实例来关停该 SDK:

void ShutdownUserMessagingPlatform() {
  ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance();
  delete consent_info;
}

使用 Future 监控异步操作

firebase::Future 可让您确定异步方法调用的完成状态。

所有异步操作的 UMP C++ 函数和方法调用都会返回 Future,还会提供“最后一条结果”函数,以便从最近的操作中检索 Future

您可以通过以下两种方式从 Future 获取结果:

  1. 调用 OnCompletion(),并传入您自己的回调函数,该函数会在操作完成时调用。
  2. 定期检查 Futurestatus()。当状态kFutureStatusPending 更改为 kFutureStatusCompleted 时,表示操作已完成。

异步操作完成后,您应该检查 Futureerror() 以获取该操作的错误代码。如果错误代码为 0kConsentRequestSuccesskConsentFormSuccess),则表示操作已成功完成;否则,请检查错误代码和 error_message(),以确定问题所在。

完成回调

以下示例展示了如何使用 OnCompletion 设置完成回调函数,该回调函数会在异步操作完成时调用。

void MyApplicationStart() {
  // [... other app initialization code ...]

  ump::ConsentInfo *consent_info = ump::ConsentInfo::GetInstance();

  // See the section below for more information about RequestConsentInfoUpdate.
  firebase::Future<void> result = consent_info->RequestConsentInfoUpdate(...);

  result.OnCompletion([](const firebase::Future<void>& req_result) {
    if (req_result.error() == ump::kConsentRequestSuccess) {
      // Operation succeeded. You can now call LoadAndShowConsentFormIfRequired().
    } else {
      // Operation failed. Check req_result.error_message() for more information.
    }
  });
}

更新循环轮询

在此示例中,异步操作在应用启动时启动后,系统会在游戏的更新循环函数(每帧运行一次)的其他位置检查结果。

ump::ConsentInfo *g_consent_info = nullptr;
bool g_waiting_for_request = false;

void MyApplicationStart() {
  // [... other app initialization code ...]

  g_consent_info = ump::ConsentInfo::GetInstance();
  // See the section below for more information about RequestConsentInfoUpdate.
  g_consent_info->RequestConsentInfoUpdate(...);
  g_waiting_for_request = true;
}

// Elsewhere, in the game's update loop, which runs once per frame:
void MyGameUpdateLoop() {
  // [... other game logic here ...]

  if (g_waiting_for_request) {
    // Check whether RequestConsentInfoUpdate() has finished.
    // Calling "LastResult" returns the Future for the most recent operation.
    firebase::Future<void> result =
      g_consent_info->RequestConsentInfoUpdateLastResult();

    if (result.status() == firebase::kFutureStatusComplete) {
      g_waiting_for_request = false;
      if (result.error() == ump::kConsentRequestSuccess) {
        // Operation succeeded. You can call LoadAndShowConsentFormIfRequired().
      } else {
        // Operation failed. Check result.error_message() for more information.
      }
    }
  }
}

如需详细了解 firebase::Future,请参阅 Firebase C++ SDK 文档GMA C++ SDK 文档

每次启动应用时,您都应使用 RequestConsentInfoUpdate()请求更新用户的意见征求信息。这决定了您的用户是否需要提供用户意见征求结果(如果尚未提供或者用户意见征求结果已过期)。

#include "firebase/gma/ump.h"

namespace ump = ::firebase::gma::ump;

void MyApplicationStart() {
  ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance();

  // Create a ConsentRequestParameters struct.
  ump::ConsentRequestParameters params;
  // Set tag for under age of consent. False means users are NOT under age
  // of consent.
  params.tag_for_under_age_of_consent = false;

  consent_info->RequestConsentInfoUpdate(params).OnCompletion(
    [](const Future<void>& result) {
      if (result.error() != ump::kConsentRequestSuccess) {
        LogMessage("Error requesting consent update: %s", result.error_message());
      } else {
        // Consent status is now available.
      }
    });
}

如需查看使用更新循环轮询(而非完成回调)检查完成情况的示例,请参阅上文

根据需要加载并显示用户意见征求表单

收到最新的用户意见征求状态后,请对ConsentInfo 类调用LoadAndShowConsentFormIfRequired() 以加载用户意见征求表单。如果需要征求用户意见,则 SDK 会加载一个表单,并立即 从提供的 FormParent中显示该表单。 Future 已完成 调用。如果不需要征得用户同意,系统会立即 Future 完成 操作。

void MyApplicationStart(ump::FormParent parent) {
  ump::ConsentInfo* consent_info = ump::ConsentInfo::GetInstance();

  // Create a ConsentRequestParameters struct..
  ump::ConsentRequestParameters params;
  // Set tag for under age of consent. False means users are NOT under age of consent.
  params.tag_for_under_age_of_consent = false;

  consent_info->RequestConsentInfoUpdate(params).OnCompletion(
    [*](const Future<void>& req_result) {
      if (req_result.error() != ump::kConsentRequestSuccess) {
        // req_result.error() is a kConsentRequestError enum.
        LogMessage("Error requesting consent update: %s", req_result.error_message());
      } else {
        consent_info->LoadAndShowConsentFormIfRequired(parent).OnCompletion(
        [*](const Future<void>& form_result) {
          if (form_result.error() != ump::kConsentFormSuccess) {
            // form_result.error() is a kConsentFormError enum.
            LogMessage("Error showing consent form: %s", form_result.error_message());
          } else {
            // Either the form was shown and completed by the user, or consent was not required.
          }
        });
      }
    });
}

如果您需要在用户做出选择或关闭表单后执行操作,请将相应逻辑放在处理 LoadAndShowConsentFormIfRequired() 返回的 Future 的代码中。

提出广告请求

在应用中请求广告之前,请检查您是否已使用 ConsentInfo::GetInstance()‑>CanRequestAds()征得用户的同意。征求用户意见时需要检查以下两个方面:

  1. 在当前会话中征求用户意见后。
  2. 调用 RequestConsentInfoUpdate()后立即执行。 可能已经在之前的会话中征得用户同意。作为延迟时间最佳做法,我们建议您不要等待回调完成,这样您就可以在应用启动后尽快开始加载广告。

如果在征求用户意见的过程中发生错误,您仍然应该尝试请求广告。UMP SDK 会使用上一个会话的用户意见征求状态。

以下完整示例使用的是更新循环轮询,但您也可以使用 OnCompletion 回调来监控异步操作。请使用最适合您的代码结构的方法。

#include "firebase/future.h"
#include "firebase/gma/gma.h"
#include "firebase/gma/ump.h"

namespace gma = ::firebase::gma;
namespace ump = ::firebase::gma::ump;
using firebase::Future;

ump::ConsentInfo* g_consent_info = nullptr;
// State variable for tracking the UMP consent flow.
enum { kStart, kRequest, kLoadAndShow, kInitGma, kFinished, kErrorState } g_state = kStart;
bool g_ads_allowed = false;

void MyApplicationStart() {
  g_consent_info = ump::ConsentInfo::GetInstance(...);

  // Create a ConsentRequestParameters struct..
  ump::ConsentRequestParameters params;
  // Set tag for under age of consent. False means users are NOT under age of consent.
  params.tag_for_under_age_of_consent = false;

  g_consent_info->RequestConsentInfoUpdate(params);
  // CanRequestAds() can return a cached value from a previous run immediately.
  g_ads_allowed = g_consent_info->CanRequestAds();
  g_state = kRequest;
}

// This function runs once per frame.
void MyGameUpdateLoop() {
  // [... other game logic here ...]

  if (g_state == kRequest) {
    Future<void> req_result = g_consent_info->RequestConsentInfoUpdateLastResult();

    if (req_result.status() == firebase::kFutureStatusComplete) {
      g_ads_allowed = g_consent_info->CanRequestAds();
      if (req_result.error() == ump::kConsentRequestSuccess) {
        // You must provide the FormParent (Android Activity or iOS UIViewController).
        ump::FormParent parent = GetMyFormParent();
        g_consent_info->LoadAndShowConsentFormIfRequired(parent);
        g_state = kLoadAndShow;
      } else {
        LogMessage("Error requesting consent status: %s", req_result.error_message());
        g_state = kErrorState;
      }
    }
  }
  if (g_state == kLoadAndShow) {
    Future<void> form_result = g_consent_info->LoadAndShowConsentFormIfRequiredLastResult();

    if (form_result.status() == firebase::kFutureStatusComplete) {
      g_ads_allowed = g_consent_info->CanRequestAds();
      if (form_result.error() == ump::kConsentRequestSuccess) {
        if (g_ads_allowed) {
          // Initialize GMA. This is another asynchronous operation.
          firebase::gma::Initialize();
          g_state = kInitGma;
        } else {
          g_state = kFinished;
        }
        // Optional: shut down the UMP SDK to save memory.
        delete g_consent_info;
        g_consent_info = nullptr;
      } else {
        LogMessage("Error displaying consent form: %s", form_result.error_message());
        g_state = kErrorState;
      }
    }
  }
  if (g_state == kInitGma && g_ads_allowed) {
    Future<gma::AdapterInitializationStatus> gma_future = gma::InitializeLastResult();

    if (gma_future.status() == firebase::kFutureStatusComplete) {
      if (gma_future.error() == gma::kAdErrorCodeNone) {
        g_state = kFinished;
        // TODO: Request an ad.
      } else {
        LogMessage("Error initializing GMA: %s", gma_future.error_message());
        g_state = kErrorState;
      }
    }
  }
}

隐私设置选项

一些用户意见征求表单要求用户随时修改同意声明。如需实现隐私权选项按钮(如果需要),请按照以下步骤操作。

要实现这一目标,需要完成以下步骤:

  1. 实现可以触发隐私权选项表单的界面元素,例如应用设置页面中的按钮。
  2. LoadAndShowConsentFormIfRequired() 完成后,请检查getPrivacyOptionsRequirementStatus() ,以确定是否显示可以呈现隐私选项表单的界面元素。
  3. 当用户与您的界面元素互动时,调用showPrivacyOptionsForm() 以显示该表单,以便用户随时更新其隐私选项。

测试

如果您希望在开发过程中测试应用中的集成,请按照以下步骤以编程方式注册测试设备。在发布应用之前,请务必移除用于设置这些测试设备 ID 的代码。

  1. 调用 RequestConsentInfoUpdate()
  2. 检查日志输出是否存在类似于以下示例的消息,该示例显示了您的设备 ID 以及如何将其添加为测试设备:

    Android

    Use new ConsentDebugSettings.Builder().addTestDeviceHashedId("33BE2250B43518CCDA7DE426D04EE231")
    to set this as a debug device.
    

    iOS

    <UMP SDK>To enable debug mode for this device,
    set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. 将测试设备 ID 复制到剪贴板。

  4. 修改代码, 将其ConsentRequestParameters.debug_settings.debug_device_ids 设置为 测试设备 ID 列表。

    void MyApplicationStart() {
      ump::ConsentInfo consent_info = ump::ConsentInfo::GetInstance(...);
    
      ump::ConsentRequestParameters params;
      params.tag_for_under_age_of_consent = false;
      params.debug_settings.debug_device_ids = {"TEST-DEVICE-HASHED-ID"};
    
      consent_info->RequestConsentInfoUpdate(params);
    }
    

强制设置地理位置

UMP SDK 可让您使用 ConsentRequestParameters.debug_settings.debug_geography来测试应用的行为,就像设备位于欧洲经济区 (EEA) 或英国一样。请注意,调试设置仅适用于测试设备。

void MyApplicationStart() {
  ump::ConsentInfo consent_info = ump::ConsentInfo::GetInstance(...);

  ump::ConsentRequestParameters params;
  params.tag_for_under_age_of_consent = false;
  params.debug_settings.debug_device_ids = {"TEST-DEVICE-HASHED-ID"};
  // Geography appears as EEA for debug devices.
  params.debug_settings.debug_geography = ump::kConsentDebugGeographyEEA

  consent_info->RequestConsentInfoUpdate(params);
}

通过 UMP SDK 测试应用时,您可能会发现重置 SDK 的状态非常有用,因为您可以模拟用户的首次安装体验。该 SDK 提供的 Reset() 方法可实现此目的。

  ConsentInfo::GetInstance()->Reset();