設定 UMP SDK

Google User Messaging Platform (UMP) SDK 是一項隱私權和訊息工具,可協助您管理隱私權選項。詳情請參閱「關於隱私權與訊息」。

建立訊息類型

在 AdMob 帳戶的「隱私權與訊息」分頁,使用可用的使用者訊息類型建立使用者訊息。UMP SDK 會嘗試顯示隱私權訊息,該訊息是根據專案中設定的 AdMob 應用程式 ID 建立。

每次啟動應用程式時,請使用 requestConsentInfoUpdate() 要求更新使用者的同意聲明資訊。這項要求會檢查下列項目:

  • 是否需要同意聲明。例如首次要求同意聲明,或先前的同意聲明決定已過期。
  • 是否需要隱私權選項進入點。部分隱私權訊息會要求應用程式允許使用者隨時修改隱私權選項。
/**
 * Requests consent information update on app launch.
 */
export function requestConsent(onComplete?: () => void) {
  requestConsentInfoUpdate({}, (error) => {
    if (error) {
      console.warn('Consent info update error:', error.message);
    } else {
      console.log('Consent info update complete.');
    }

    // Load and show consent form if required.
    loadAndPresentConsentForm(onComplete);
  });
}

載入並顯示隱私權訊息表單

取得最新同意聲明狀態後,請呼叫 loadAndShowConsentFormIfRequired(),載入收集使用者同意聲明所需的表單。載入後,表單會立即顯示。

/**
 * Loads and presents the privacy message form if required to collect user consent.
 */
export function loadAndPresentConsentForm(onComplete?: () => void) {
  loadAndShowConsentFormIfRequired((formError) => {
    if (formError) {
      console.warn('Consent form error:', formError.message);
    } else {
      console.log('Consent gathering complete.');
    }

    // Execute logic that depends on consent state (for example, initialize the SDK).
    onComplete?.();
  });
}

隱私權選項

部分隱私權訊息表單會從發布商顯示的隱私權選項進入點顯示,讓使用者隨時管理隱私權選項。如要進一步瞭解使用者在隱私權選項進入點看到的訊息,請參閱「可用的使用者訊息類型」。

確認是否需要提供隱私權選項進入點

呼叫 requestConsentInfoUpdate() 後,請檢查 getPrivacyOptionsRequirementStatus(),判斷應用程式是否需要隱私權選項進入點。如果需要,請在應用程式中加入可見且可互動的 UI 元素,用於顯示隱私權選項表單。如果不需要隱私權進入點,請將 UI 元素設為不可見且無法互動。

/**
 * Helper to determine if the privacy options entry point is required.
 */
export function isPrivacyOptionsRequired(): boolean {
  return (
    getPrivacyOptionsRequirementStatus() ===
    PrivacyOptionsRequirementStatus.REQUIRED
  );
}

如需隱私權選項規定狀態的完整清單,請參閱 PrivacyOptionsRequirementStatus。

顯示隱私權選項表單

使用者與元素互動時,顯示隱私權選項表單:

/**
 * Renders a privacy options button if required by user consent policy.
 */
export function PrivacyOptionsButton({
  onDismissed,
}: {
  onDismissed?: (error?: FormError) => void;
}) {
  const isRequired =
    getPrivacyOptionsRequirementStatus() ===
    PrivacyOptionsRequirementStatus.REQUIRED;

  if (!isRequired) {
    return null;
  }

  const handleShowPrivacyOptions = () => {
    showPrivacyOptionsForm((error) => {
      if (error) {
        console.error('Failed to show privacy options form:', error.message);
      } else {
        console.log('Privacy options form dismissed.');
      }

      // Execute custom logic after form is dismissed.
      onDismissed?.(error);
    });
  };

  return <Button title="Privacy Settings" onPress={handleShowPrivacyOptions} />;
}

在取得使用者同意聲明後請求廣告

請求廣告前,請使用 canRequestAds() 確認是否已取得使用者同意:

/**
 * Checks whether user consent allows requesting ads and initializes the SDK.
 */
let isMobileAdsInitialized = false;

export function initializeMobileAdsSdkIfConsentGiven() {
  if (canRequestAds()) {
    if (!isMobileAdsInitialized) {
      isMobileAdsInitialized = true;
      initialize({}, (status) => {
        console.log('Google Mobile Ads SDK initialized:', status);
      });
    }
  }
}

以下列出幾個地方,可供您檢查是否能在收集同意聲明時請求廣告:

  • UMP SDK 在目前工作階段收集同意聲明後。
  • 呼叫 requestConsentInfoUpdate() 後立即執行。UMP SDK 可能已在先前的應用程式工作階段中取得同意聲明。

如果收集同意聲明的過程發生錯誤,請檢查是否能請求廣告。UMP SDK 會使用先前應用程式工作階段的同意聲明狀態。

避免重複的廣告請求作業

在收集同意聲明並呼叫 requestConsentInfoUpdate() 後,您會檢查 canRequestAds(),請確保邏輯能防止重複的廣告請求,以免兩次檢查都傳回 true。例如,使用布林值變數。

測試

如要在開發應用程式時測試整合,請按照下列步驟,透過程式輔助註冊測試裝置。發布應用程式前,請務必先移除用來設定測試裝置 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. 修改程式碼以呼叫 consentDebugSettings.testDeviceIdentifiers,並傳遞測試裝置 ID 清單。

    /**
     * Registers a test device for testing consent flows.
     */
    export function configureTestDevice() {
      requestConsentInfoUpdate(
        {
          consentDebugSettings: {
            debugGeography: DebugGeography.DISABLED,
            testDeviceIdentifiers: ["TEST_DEVICE_HASHED_ID"],
          },
        },
        (error) => {
          if (!error) {
            console.log('Test device registered.');
          }
        },
      );
    }

強制指定地理位置

UMP SDK 可讓您使用 DebugGeography 測試應用程式行為,模擬裝置位於歐洲經濟區 (EEA)、英國和瑞士等不同地區的情況。請注意,偵錯設定僅適用於測試裝置。

/**
 * Configures debug settings to force EEA geography on a test device.
 */
export function configureDebugGeography() {
  requestConsentInfoUpdate(
    {
      consentDebugSettings: {
        debugGeography: DebugGeography.EEA,
        testDeviceIdentifiers: ["TEST_DEVICE_HASHED_ID"],
      },
    },
    (error) => {
      if (!error) {
        console.log('Consent debug test configuration loaded.');
      }
    },
  );
}

使用 UMP SDK 測試應用程式時,建議您重設 SDK 狀態,以便模擬使用者首次安裝的體驗。SDK 提供 reset() 方法來執行這項操作。

/**
 * Resets consent state for testing purposes.
 */
export function resetConsentState() {
  reset();
}