開始使用

首先,請將 Android PAL SDK 新增至應用程式。

將 Android PAL SDK 新增為程式庫

自 18.0.0 版起,PAL SDK 就會由 Google 的 Maven 存放區代管,您可以按照下列方式將其新增至應用程式:

app/build.gradle

...
dependencies {
    implementation 'com.google.android.gms:play-services-pal:22.0.0'
    ...
}

或者,您也可以從 Google 的 Maven 存放區下載 PAL SDK,然後手動將其新增至應用程式。

產生 Nonce

「Nonce」是指 PAL 使用 NonceLoader 產生的單一加密字串。PAL SDK 要求每個新的串流要求都必須附上新產生的 Nonce。不過,同一個串流中的多個廣告請求可以重複使用 Nonce。如要使用 PAL SDK 產生 Nonce,請變更 MyActivity.java。如要查看使用 PAL 產生 Nonce 的範例應用程式,請從 GitHub 下載 Android 範例。

您必須先匯入 PAL SDK,建立一些私人資源來儲存 NonceLoaderNonceManager,然後再初始化 NonceLoader。

除非應用程式有多個頁面或等同的結構體,否則建議您只為應用程式中的每個使用者工作階段建立一個 NonceLoader 類別的例項。這樣一來,網頁 Correlator (&correlator) 就會在網頁的整個生命週期或使用者在應用程式中的工作階段中保持不變。您仍可控制串流 Correlator (&scor),每個新的串流都應重設一次。

同一個串流的所有廣告請求都應共用相同的 NonceLoader 和串流 Correlator 值,才能讓展示頻率上限和競爭排除功能正常運作。

import android.app.Activity;
import android.os.Bundle;
import com.google.ads.interactivemedia.pal.NonceLoader;
import com.google.ads.interactivemedia.pal.NonceManager;
import com.google.ads.interactivemedia.pal.NonceRequest;
import com.google.ads.interactivemedia.pal.ConsentSettings;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.HashSet;
import java.util.Set;

public class MainActivity extends Activity {
...
  private NonceLoader nonceLoader;
  private NonceManager nonceManager = null;
  private ConsentSettings consentSettings;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // The default value for allowStorage() is false, but can be
    // changed once the appropriate consent has been gathered. The
    // getConsentToStorage() method is a placeholder for the publisher's own
    // method of obtaining user consent, either by integrating with a CMP or
    // based on other methods the publisher chooses to handle storage consent.

    boolean isConsentToStorage = getConsentToStorage();

    videoView = findViewById(R.id.video_view);
    videoView.setOnTouchListener(this::onVideoViewTouch);

    consentSettings = ConsentSettings.builder()
            .allowStorage(isConsentToStorage)
            .build();

    // It is important to instantiate the NonceLoader as early as possible to
    // allow it to initialize and preload data for a faster experience when
    // loading the NonceManager. A new NonceLoader will need to be instantiated
    //if the ConsentSettings change for the user.
    nonceLoader = new NonceLoader(this, consentSettings);
    ...
  }

接著,建立函式來觸發 Nonce 產生作業。您只需要一個 Nonce,即可處理單一串流播放中的所有廣告請求。為了測試,您可以在點選測試應用程式中的按鈕時呼叫這個函式。此處設定的 NonceRequest 參數為範例參數。您應根據自己的應用程式特性設定參數。

此函式會非同步觸發 Nonce 產生作業,因此您需要實作 AsyncTask,以便處理 Nonce 要求的成功或失敗情形:

public void generateNonceForAdRequest() {
  Set supportedApiFrameWorksSet = new HashSet();
  // The values 2, 7, and 9 correspond to player support for VPAID 2.0,
  // OMID 1.0, and SIMID 1.1.
  supportedApiFrameWorksSet.add(2);
  supportedApiFrameWorksSet.add(7);
  supportedApiFrameWorksSet.add(9);

  NonceRequest nonceRequest = NonceRequest.builder()
      .descriptionURL("https://example.com/content1")
      .iconsSupported(true)
      .omidPartnerVersion("6.2.1")
      .omidPartnerName("Example Publisher")
      .playerType("ExamplePlayerType")
      .playerVersion("1.0.0")
      .ppid("testPpid")
      .sessionId("Sample SID")
      .supportedApiFrameworks(supportedApiFrameWorksSet)
      .videoPlayerHeight(480)
      .videoPlayerWidth(640)
      .willAdAutoPlay(true)
      .willAdPlayMuted(false)
      .build();
  NonceCallbackImpl callback = new NonceCallbackImpl();
  nonceLoader
      .loadNonceManager(nonceRequest)
      .addOnSuccessListener(callback)
      .addOnFailureListener(callback);
}

private class NonceCallbackImpl implements OnSuccessListener<NonceManager>, OnFailureListener {
  @Override
  public void onSuccess(NonceManager manager) {
    nonceManager = manager;
    String nonceString = manager.getNonce();
    Log.i("PALSample", "Generated nonce: " + nonceString);
    // from here you would trigger your ad request and move on to initialize content
  }

  @Override
  public void onFailure(Exception error) {
    Log.e("PALSample", "Nonce generation failed: " + error.getMessage());
  }
}

建立 Nonce 管理員後,您隨時可以使用 nonceManager.getNonce() 擷取 Nonce。

將 Nonce 附加至廣告請求

如要使用產生的 Nonce,請在發出廣告請求前,將 givn 參數和 Nonce 值附加至廣告代碼。

/**
 * The ad tag for your ad request, for example:
 * https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external\
 * /single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1\
 * &cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator=
 *
 * For more sample ad tags, see
 * developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags
 */
private static final String DEFAULT_AD_TAG = "Your ad tag";
...
@Override
public void onSuccess(NonceManager manager) {
  nonceManager = manager;
  String nonceString = manager.getNonce();
  Log.i("PALSample", "Generated nonce: " + nonceString);
  // Append the nonce to the ad tag URL.
  makeAdRequest(DEFAULT_AD_TAG + "&givn=" + nonceString);
}

追蹤播放事件

最後,您需要為播放器實作各種事件處理常式。為了測試,您可以將這些事件附加至按鈕點擊事件,但在實際實作中,這些事件會由適當的播放器事件觸發:

public void sendAdClick() {
  if (nonceManager != null) {
    nonceManager.sendAdClick();
  }
}

public void sendPlaybackStart() {
  if (nonceManager != null) {
    nonceManager.sendPlaybackStart();
  }
}

public void sendPlaybackEnd() {
  if (nonceManager != null) {
    nonceManager.sendPlaybackEnd();
  }
}

public void onVideoViewTouch(MotionEvent e) {
  if (nonceManager != null) {
    nonceManager.sendTouch(e);
  }
}

以下是實作中呼叫每個函式的時機:

  • sendPlaybackStart():影片播放工作階段開始時
  • sendPlaybackEnd():影片播放工作階段結束時
  • sendAdClick():觀眾每次點按廣告
  • sendTouch():每次與播放器互動時

(選用) 透過第三方廣告伺服器傳送 Google Ad Manager 信號

設定第三方廣告伺服器與 Google Ad Manager 搭配運作時,請參閱伺服器的說明文件,擷取並轉送每個廣告請求中的 Nonce 值。提供的範例是包含 Nonce 參數的廣告請求網址。Nonce 參數會從 PAL SDK 傳播至中介伺服器,然後傳播至 Ad Manager,以便提升廣告收益。

請設定第三方廣告伺服器,在伺服器向 Ad Manager 提出的要求中加入 Nonce。以下是第三方廣告伺服器內設定的廣告代碼範例:

'https://pubads.serverside.net/gampad/ads?givn=%%custom_key_for_google_nonce%%&...'

詳情請參閱 Google Ad Manager 伺服器端導入指南

Ad Manager 會尋找 givn= 來識別 Nonce 值。第三方廣告伺服器需要支援自身的部分巨集 (例如 %%custom_key_for_google_nonce%%),並將其替換為您在上一個步驟中提供的 Nonce 查詢參數。如需進一步瞭解如何完成這項操作,請參閱第三方廣告伺服器的說明文件。