開始使用

第一步是在應用程式中加入 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:20.2.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) 在網頁或應用程式的生命週期中保持不變。您仍可掌控串流關聯器 (&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。為了進行測試,您可以在測試應用程式中點選按鈕時呼叫此函式。

這個函式會以非同步的方式觸發 Nonce 產生,因此您需要實作 AsyncTask 來處理 Nonce 要求的成功或失敗:

public void generateNonceForAdRequest() {
  Set supportedApiFrameWorksSet = new HashSet();
  supportedApiFrameWorksSet.add(2);
  supportedApiFrameWorksSet.add(7);
  supportedApiFrameWorksSet.add(9);

  NonceRequest nonceRequest = NonceRequest.builder()
      .descriptionURL("https://example.com/content1")
      .iconsSupported(true)
      .omidVersion("1.0.0")
      .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(true)
      .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 查詢參數。如要進一步瞭解如何完成這項作業,請參閱第三方廣告伺服器的說明文件。