시작하기

첫 번째 단계는 앱에 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)가 변경되지 않습니다. 새 스트림마다 한 번씩 재설정해야 하는 스트림 상관자 (&scor)를 계속 제어할 수 있습니다.

최대 게재빈도 설정 및 경쟁 제외 기능이 제대로 작동하려면 동일한 스트림의 모든 광고 요청이 동일한 NonceLoader 및 스트림 상관자 값을 공유해야 합니다.

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 매개변수가 포함된 광고 요청 URL입니다. 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 쿼리 매개변수로 대체해야 합니다. 이를 수행하는 방법에 대한 자세한 내용은 외부 광고 서버 설명서를 참조하세요.