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);...}
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());}}
/** * 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);}
[[["容易理解","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 (世界標準時間)。"],[[["\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."]]