'nonce'는 PAL에서 NonceLoader를 사용하여 생성한 단일 암호화된 문자열입니다.
PAL SDK에서는 각 새 스트림 요청에 새로 생성된 nonce가 포함되어야 합니다. 그러나 nonce는 동일한 스트림 내의 여러 광고 요청에 재사용될 수 있습니다. PAL SDK를 사용하여 nonce를 생성하려면 MyActivity.java를 변경합니다. PAL을 사용하여 nonce를 생성하는 샘플 앱을 보려면 GitHub에서 Android 예시를 다운로드하세요.
먼저 PAL SDK를 가져오고 NonceLoader 및 NonceManager를 저장할 비공개 속성을 만든 다음 NonceLoader를 초기화해야 합니다.
앱에 여러 페이지 또는 이에 상응하는 구성이 없는 한 앱의 각 사용자 세션에 대해 NonceLoader 클래스의 인스턴스를 하나만 만드는 것이 좋습니다. 이렇게 하면 페이지 또는 앱에서 사용자의 세션이 유지되는 동안 페이지 상관자 (&correlator)가 변경되지 않습니다. 새 스트림마다 한 번씩 재설정해야 하는 스트림 상관자 (&scor)는 계속 제어할 수 있습니다.
최대 게재빈도 설정 및 경쟁 제외 기능이 제대로 작동하려면 동일한 스트림의 모든 광고 요청이 동일한 NonceLoader 및 스트림 상관자 값을 공유해야 합니다.
importandroid.app.Activity;importandroid.os.Bundle;importcom.google.ads.interactivemedia.pal.NonceLoader;importcom.google.ads.interactivemedia.pal.NonceManager;importcom.google.ads.interactivemedia.pal.NonceRequest;importcom.google.ads.interactivemedia.pal.ConsentSettings;importcom.google.android.gms.tasks.OnFailureListener;importcom.google.android.gms.tasks.OnSuccessListener;importjava.util.HashSet;importjava.util.Set;publicclassMainActivityextendsActivity{...privateNonceLoadernonceLoader;privateNonceManagernonceManager=null;privateConsentSettingsconsentSettings;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){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.booleanisConsentToStorage=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=newNonceLoader(this,consentSettings);...}
그런 다음 nonce 생성을 트리거하는 함수를 만듭니다. 단일 스트림 재생의 모든 광고 요청에는 nonce가 하나만 필요합니다. 테스트 목적으로 테스트 앱에서 버튼을 클릭할 때 이 함수를 호출할 수 있습니다. 여기에 설정된 NonceRequest 매개변수는 예시 매개변수입니다. 자체 앱 특성에 따라 매개변수를 설정해야 합니다.
이 함수는 nonce 생성을 비동기식으로 트리거하므로 nonce 요청의 성공 또는 실패를 처리하는 AsyncTask를 구현해야 합니다.
publicvoidgenerateNonceForAdRequest(){SetsupportedApiFrameWorksSet=newHashSet();// 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);NonceRequestnonceRequest=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();NonceCallbackImplcallback=newNonceCallbackImpl();nonceLoader.loadNonceManager(nonceRequest).addOnSuccessListener(callback).addOnFailureListener(callback);}privateclassNonceCallbackImplimplementsOnSuccessListener<NonceManager>,OnFailureListener{@OverridepublicvoidonSuccess(NonceManagermanager){nonceManager=manager;StringnonceString=manager.getNonce();Log.i("PALSample","Generated nonce: "+nonceString);// from here you would trigger your ad request and move on to initialize content}@OverridepublicvoidonFailure(Exceptionerror){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 */privatestaticfinalStringDEFAULT_AD_TAG="Your ad tag";...@OverridepublicvoidonSuccess(NonceManagermanager){nonceManager=manager;StringnonceString=manager.getNonce();Log.i("PALSample","Generated nonce: "+nonceString);// Append the nonce to the ad tag URL.makeAdRequest(DEFAULT_AD_TAG+"&givn="+nonceString);}
재생 이벤트 추적
마지막으로 플레이어에 다양한 이벤트 핸들러를 구현해야 합니다. 테스트 목적으로는 버튼 클릭 이벤트에 연결할 수 있지만 실제 구현에서는 적절한 플레이어 이벤트에 의해 트리거됩니다.
Google Ad Manager와 호환되도록 서드 파티 광고 서버를 설정할 때는 서버 문서를 참고하여 각 광고 요청에서 nonce 값을 캡처하고 전달합니다. 제공된 예는 nonce 매개변수가 포함된 광고 요청 URL입니다. nonce 매개변수는 PAL SDK에서 중간 서버를 거쳐 Ad Manager로 전파되어 더 나은 수익 창출을 가능하게 합니다.
서버의 Ad Manager 요청에 nonce를 포함하도록 서드 파티 광고 서버를 구성합니다. 다음은 서드 파티 광고 서버 내에서 구성된 광고 태그의 예입니다.
Ad Manager는 givn=를 찾아 nonce 값을 식별합니다. 서드 파티 광고 서버는 자체 매크로(예: %%custom_key_for_google_nonce%%)를 지원하고 이를 이전 단계에서 제공한 nonce 쿼리 매개변수로 대체해야 합니다. 이를 실행하는 방법에 관한 자세한 내용은 서드 파티 광고 서버 문서를 참고하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-21(UTC)"],[[["\u003cp\u003eThe Android PAL SDK, hosted on Google's Maven repository, can be added to your app as a library by including \u003ccode\u003eimplementation 'com.google.android.gms:play-services-pal:22.0.0'\u003c/code\u003e in your \u003ccode\u003eapp/build.gradle\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eA unique, encrypted "nonce" string, generated by the PAL SDK's \u003ccode\u003eNonceLoader\u003c/code\u003e, is required for each new stream request and can be reused for multiple ad requests within the same stream.\u003c/p\u003e\n"],["\u003cp\u003eYou need to initialize the \u003ccode\u003eNonceLoader\u003c/code\u003e as early as possible, ideally creating only one instance per user session, to ensure consistent page correlator values and shared stream correlator values for frequency capping and competitive exclusion features.\u003c/p\u003e\n"],["\u003cp\u003eTo use the generated nonce, you must append it to your ad tag with the \u003ccode\u003egivn\u003c/code\u003e parameter, replacing any prior use of the \u003ccode\u003epaln\u003c/code\u003e parameter, and include the nonce value when making ad requests.\u003c/p\u003e\n"],["\u003cp\u003ePlayback events such as start, end, ad clicks, and touch interactions must be tracked and sent to the \u003ccode\u003eNonceManager\u003c/code\u003e using \u003ccode\u003esendPlaybackStart()\u003c/code\u003e, \u003ccode\u003esendPlaybackEnd()\u003c/code\u003e, \u003ccode\u003esendAdClick()\u003c/code\u003e, and \u003ccode\u003esendTouch()\u003c/code\u003e, respectively.\u003c/p\u003e\n"]]],["Integrate the Android PAL SDK by adding it as a library via Google's Maven repository in `build.gradle`. Generate a unique nonce using `NonceLoader` for each stream, reusing it within the same stream. Initialize `NonceLoader` with `ConsentSettings`, create a `NonceRequest`, and use `loadNonceManager` with callbacks for success/failure. Retrieve the nonce using `nonceManager.getNonce()`, appending it to the ad tag URL with `&givn=`. Finally, implement event handlers for ad clicks, playback start/end, and touches using `nonceManager`.\n"],null,["# Get Started\n\nThe first step is to add the Android PAL SDK to your app.\n\nAdd the Android PAL SDK as a library\n------------------------------------\n\nAs of version 18.0.0, the PAL SDK is hosted on Google's Maven repository and\ncan be added to your app as follows:\n\n**app/build.gradle** \n\n ...\n dependencies {\n implementation 'com.google.android.gms:play-services-pal:22.1.0'\n ...\n }\n\nAlternatively, the PAL SDK can be downloaded from [Google's Maven repository](https://maven.google.com/web/index.html?q=pal#com.google.android.gms:play-services-pal:22.1.0) and manually added to your app.\n\nGenerate nonce\n--------------\n\nA \"nonce\" is a single encrypted string generated by PAL using the `NonceLoader`.\nThe PAL SDK requires each new stream request to be accompanied by a newly\ngenerated nonce. However, nonces can be reused for multiple ad requests within\nthe same stream. To generate a nonce using the PAL SDK, make changes to\n`MyActivity.java`. To see a sample app that uses PAL to generate a nonce,\ndownload the Android example from\n[GitHub](//github.com/googleads/googleads-pal).\n\nYou first need to import the PAL SDK, create some private properties to store\nyour `NonceLoader` and `NonceManager`, and then initialize your NonceLoader.\n\nWe recommend that you create only one instance of the `NonceLoader` class for\neach user session in your app unless your app has multiple pages or equivalent\nconstructs. This keeps the page correlator (`&correlator`) unchanged for the\nlifetime of a page or a user's session on the app. You still have control over\nthe stream correlator (`&scor`) which should be reset once for each new stream.\n\nAll ad requests of the same stream should share the same `NonceLoader` and\nstream correlator value for frequency capping and competitive exclusion\nfeatures to work properly. \n\n import android.app.Activity;\n import android.os.Bundle;\n import com.google.ads.interactivemedia.pal.NonceLoader;\n import com.google.ads.interactivemedia.pal.NonceManager;\n import com.google.ads.interactivemedia.pal.NonceRequest;\n import com.google.ads.interactivemedia.pal.ConsentSettings;\n import com.google.android.gms.tasks.OnFailureListener;\n import com.google.android.gms.tasks.OnSuccessListener;\n import java.util.HashSet;\n import java.util.Set;\n\n public class MainActivity extends Activity {\n ...\n private NonceLoader nonceLoader;\n private NonceManager nonceManager = null;\n private ConsentSettings consentSettings;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n // The default value for allowStorage() is false, but can be\n // changed once the appropriate consent has been gathered. The\n // getConsentToStorage() method is a placeholder for the publisher's own\n // method of obtaining user consent, either by integrating with a CMP or\n // based on other methods the publisher chooses to handle storage consent.\n boolean isConsentToStorage = getConsentToStorage();\n videoView = findViewById(R.id.video_view);\n videoView.setOnTouchListener(this::onVideoViewTouch);\n consentSettings = ConsentSettings.builder()\n .allowStorage(isConsentToStorage)\n .build();\n // It is important to instantiate the NonceLoader as early as possible to\n // allow it to initialize and preload data for a faster experience when\n // loading the NonceManager. A new NonceLoader will need to be instantiated\n //if the ConsentSettings change for the user.\n nonceLoader = new NonceLoader(this, consentSettings);\n ...\n }\n\nNext, create a function to trigger nonce generation. You only need one nonce\nfor all the ad requests in a single stream playback. For testing purposes, you\ncan call this function when clicking a button in your test app. The\n`NonceRequest` parameters set here are example parameters. You should set your\nparameters based on your own app characteristics.\n\nThis function triggers nonce generation asynchronously, so you need to\nimplement an `AsyncTask` to handle success or failure of the nonce request: \n\n public void generateNonceForAdRequest() {\n Set supportedApiFrameWorksSet = new HashSet();\n // The values 2, 7, and 9 correspond to player support for VPAID 2.0,\n // OMID 1.0, and SIMID 1.1.\n supportedApiFrameWorksSet.add(2);\n supportedApiFrameWorksSet.add(7);\n supportedApiFrameWorksSet.add(9);\n\n NonceRequest nonceRequest = NonceRequest.builder()\n .descriptionURL(\"https://example.com/content1\")\n .iconsSupported(true)\n .omidPartnerVersion(\"6.2.1\")\n .omidPartnerName(\"Example Publisher\")\n .playerType(\"ExamplePlayerType\")\n .playerVersion(\"1.0.0\")\n .ppid(\"testPpid\")\n .sessionId(\"Sample SID\")\n .supportedApiFrameworks(supportedApiFrameWorksSet)\n .videoPlayerHeight(480)\n .videoPlayerWidth(640)\n .willAdAutoPlay(true)\n .willAdPlayMuted(false)\n .build();\n NonceCallbackImpl callback = new NonceCallbackImpl();\n nonceLoader\n .loadNonceManager(nonceRequest)\n .addOnSuccessListener(callback)\n .addOnFailureListener(callback);\n }\n\n private class NonceCallbackImpl implements OnSuccessListener\u003cNonceManager\u003e, OnFailureListener {\n @Override\n public void onSuccess(NonceManager manager) {\n nonceManager = manager;\n String nonceString = manager.getNonce();\n Log.i(\"PALSample\", \"Generated nonce: \" + nonceString);\n // from here you would trigger your ad request and move on to initialize content\n }\n\n @Override\n public void onFailure(Exception error) {\n Log.e(\"PALSample\", \"Nonce generation failed: \" + error.getMessage());\n }\n }\n\nOnce a nonce manager is created, the nonce can be retrieved at any time using\n`nonceManager.getNonce()`.\n\nAttach nonce to the ad request\n------------------------------\n\nTo use the generated nonce, append your ad tag with a `givn` parameter and the\nnonce value before making your ad requests.\n**Caution:** If you previously provided a nonce using the `paln` parameter, it is strongly recommended to migrate to `givn` and stop sending `paln`. If both parameters are included, it is undefined behavior regarding which nonce one is used. \n\n /**\n * The ad tag for your ad request, for example:\n * https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external\\\n * /single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1\\\n * &cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator=\n *\n * For more sample ad tags, see\n * developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags\n */\n private static final String DEFAULT_AD_TAG = \"Your ad tag\";\n ...\n @Override\n public void onSuccess(NonceManager manager) {\n nonceManager = manager;\n String nonceString = manager.getNonce();\n Log.i(\"PALSample\", \"Generated nonce: \" + nonceString);\n // Append the nonce to the ad tag URL.\n makeAdRequest(DEFAULT_AD_TAG + \"\\&givn=\" + nonceString);\n }\n\nTrack playback events\n---------------------\n\nLastly, you need to implement various event handlers for your player. For\ntesting purposes, you can attach these to button click events, but in a real\nimplementation, these would be triggered by the appropriate player events: \n\n public void sendAdClick() {\n if (nonceManager != null) {\n nonceManager.sendAdClick();\n }\n }\n\n public void sendPlaybackStart() {\n if (nonceManager != null) {\n nonceManager.sendPlaybackStart();\n }\n }\n\n public void sendPlaybackEnd() {\n if (nonceManager != null) {\n nonceManager.sendPlaybackEnd();\n }\n }\n\n public void onVideoViewTouch(MotionEvent e) {\n if (nonceManager != null) {\n nonceManager.sendTouch(e);\n }\n }\n\nHere is when to call each function in your implementation:\n\n- `sendPlaybackStart()`: When your video playback session begins\n- `sendPlaybackEnd()`: When your video playback session comes to an end\n- `sendAdClick()`: Each time the viewer clicks an ad\n- `sendTouch()`: On every touch interaction with the player\n\n(Optional) Send Google Ad Manager signals through third-party ad servers\n------------------------------------------------------------------------\n\nWhen you set up your third-party ad server to work with Google Ad Manager, refer\nto your server's documentation to capture and forward the nonce value in each ad\nrequest. The provided example is of an ad request URL with the nonce parameter\nincluded. The nonce parameter propagates from the PAL SDK, through your\nintermediary servers, and then to Ad Manager, enabling better monetization.\n| **Note:** If you use multiple third-party solutions, for example, a third-party SSAI server calling another third-party ad server, you need to make sure the PAL SDK's encrypted nonce is forwarded to each third party.\n\nConfigure your third-party ad server to include the nonce in the server's\nrequest to Ad Manager. Here's an example of an ad tag configured inside of the\nthird-party ad server: \n\n 'https://pubads.serverside.net/gampad/ads?givn=%%custom_key_for_google_nonce%%&...'\n\nFor more details, see the [Google Ad Manager Server-side implementation\nguide](//support.google.com/admanager/answer/10668760).\n\nAd Manager looks for `givn=` to identify the nonce value. The third-party ad\nserver needs to support some macro of its own, such as\n`%%custom_key_for_google_nonce%%`, and replace it with the nonce query parameter\nyou provided in the previous step. More information on how to accomplish this\nshould be available in the third-party ad server's documentation."]]