Initialize the SDK
Overview
The OneTrust SDK retrieves and saves all the data needed to display the CMP UI and collect consent for the purposes, vendors and SDKs used by the application. The data returned is determined by the configurations made in the OneTrust tenant/admin console.
Before the SDK can be successfully initialized, ensure that the appropriate SDK data version has been published in the OneTrust tenant/admin console. If it has not been published, there will be no data to retrieve.
For more information on instructions, see Publish Changes.
Start the SDK
This method initializes the SDK and fetches banner data.
OTPublishersHeadlessSDK otPublishersHeadlessSDK = new OTPublishersHeadlessSDK(this);
otPublishersHeadlessSDK.startSDK(domainURL, domainId, languageCode, sdkParams, false, new OTCallback() {
@Override
public void onSuccess(@NonNull OTResponse otSuccessResponse) {
String otData = otSuccessResponse.getResponseData();
//consent logic
//UI logic
}
@Override
public void onFailure(@NonNull OTResponse otErrorResponse) {
int errorCode = otErrorResponse.getResponseCode();
String errorDetails = otErrorResponse.getResponseMessage();
// Use toString() to log complete OT response
Log.i(LOG_TAG, otErrorResponse.toString());
}
});
Parameter | Description | Required |
---|---|---|
domainUrl | CDN location where data needs to be fetched. (Usually, but not always, cdn.cookielaw.org .You can retrieve this from your OneTrust tenant > Mobile App Consent > SDKs > Your App > Instructions. | Yes |
domainId | The Application ID (retrieved from OneTrust admin console) You can retrieve this from your OneTrust tenant > Mobile App Consent > SDKs > Your App > Instructions. A test and production app ID is available for staging and production. | Yes |
languageCode | 2-digit or 4-digit (in the case of advanced languages) ISO language code used to return content in a specific langauge. Note: Any language code format not listed in the OneTrust environment will be considered as an invalid input. Note: If the languageCode passed by your application is valid, but does not match a language configuration added in your template, the SDK will return content in the default language configured (usually, but not always, English). | Yes |
sdkParams | A parameter of type OTSdkParams which contains other optional SDK params like like country code, region code, cross device profiles, etc. See below for more details. Pass in null if not utilized. | No |
loadOffline | Set to true to load Offline Mode data. | No |
OTCallback | The block of code to be triggered once the execution is complete. Also contains a response object that returns the status, error, and response string. More detail below. | Yes |
Response Object
Field | Description | Type |
---|---|---|
getResponseCode() | Represents an integer value for the HTTP response code. | Int |
getResponseType() | Represents a success or error response type. | String |
getResponseMessage() | Represents details about the response. | String |
getResponseData() | Represents the server response received while starting the SDK. | String |
OTSdkParams
OTSdkParams
Parameter | Description |
---|---|
setOTCountryCode | Two-letter ISO 3166-2 country code. This can be used to bypass the automatic geo-ip lookup performed by the SDK. |
setOTRegionCode | Two-letter state code used alongside countryCode. |
shouldCreateProfile | When set to "true" , the SDK will create data subject profiles for use with Cross Device Consent. If Cross Device Consent is not in scope, disregard this. For more information on usage, see here. |
setProfileSyncParams | Sets the data subject profile values for Cross Device Consent. If Cross Device Consent is not in scope, disregard this. For more information on usage, see here. |
setUCPurposeFlow | When set to "true" , the SDK will fetch data for Universal Consent Purposes as configured in the OneTrust Admin Portal. Note : When set to "true" , only Universal Consent data will be fetched. Banner data will not be downloaded. |
OTSdkParams sdkParams = OTSdkParams.SdkParamsBuilder.newInstance()
.setOTCountryCode("US")
.setOTRegionCode("CA")
.build();
Things to Know
- We recommended calling
startSDK
on every app launch to ensure data is fetched regularly.- The call will fail if there are internet connectivity issues or an invalid storage URL/domain identifier/language code is passed.
- By default, the data from the
ResponseData
returned as part of theResponseObejct
in theonSuccess
handler is from the Banner API.
As of 202507.1.0,
startSDK
will no longer fetch all data for the CMP at once. Instead, data will be downloaded on the fly. For example, Preference Center or Vendor List data will only be fetched if the user tries to navigate to those pages.
After the SDK has successfully fetched any of the API data at least once (e.g. banner data, preference center data, etc.), it caches it locally on the device. If the initialization fails the next time, users will still be able to access the CMP UI and make consent choices.
On each successful call of
startSDK
as the banner data is fetched, the SDK clears the cached preference center and vendor list data. These data sets are only fetched again if the user navigates to those pages.
For more information on Cross Device Consent, see Cross Domain and Cross Device Consent.
Passing Custom Geolocation
By default, the OneTrust SDK determines country and region code for a user based on a geo-ip lookup during the startSDK
call to deliver a certain consent experience. If you choose to perform your own geolocation lookup, you can pass in your own countryCode
and regionCode
parameters with OTSdkParams
here.
Retrieving User Location
The SDK returns the location where data was last downloaded and can be used to determine user location. Returns a string.
OTPublishersHeadlessSDK otPublishersHeadlessSDK = new OTPublishersHeadlessSDK(this);
otPublishersHeadlessSDK.getLastDataDownloadedLocation().country;
otPublishersHeadlessSDK.getLastDataDownloadedLocation().state;
The SDK returns the location where the user last interacted with the SDK UI and provided consent. Returns a string.
OTPublishersHeadlessSDK otPublishersHeadlessSDK = new OTPublishersHeadlessSDK(this);
otPublishersHeadlessSDK.getLastUserConsentedLocation().country;
otPublishersHeadlessSDK.getLastUserConsentedLocation().state;
Set Offline Data
The offline data mode can be used to initialize the OneTrust SDK without any connection by having the application pass in the CMP data required.
If the loadOffline parameter in startSDK
is passed as false
and the network call to OneTrust fails (e.g. e.g. no internet connection, outage, etc.), the SDK will try using the offline data set up using otPublishersHeadlessSDK.setOfflineData()
. If no data is available, the SDK will fail to initialize.
If the loadOffline parameter is passed as true
, the SDK will only use the offline data set up using otPublishersHeadlessSDK.setOfflineData()
. If no data is available, the SDK will fail to initialize.
The SDK can only ingest one data set at a time. This means we can only support one geolocation rule, one template, and one language. If your app needs to support multiple experiences, you'll need to store each variation and pass in the appropriate data set accordingly.
Fetching OneTrust Data
There are three separate endpoints to fetch the Banner, Preference Center and Vendor data. See below for tech specs and API reference:
- Fetch the Banner JSON: Get Banner Data
- Fetch the Preference Center JSON: Get Preference Center Data
- Fetch the Vendors JSON: Get IAB and Google Vendors
- This endpoint and data is only needed if you're using the IAB TCF framework
After retrieving all JSON data needed, supply it to the SDK.
Reading Asset File - Code Snippet
@Nullable
String readAssetFile(@NonNull Context context, @NonNull String fileName) {
String fileContent = null;
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(fileName);
int size = inputStream.available();
byte[] buffer = new byte[size];
int isRead = inputStream.read(buffer);
Log.v(LOG_TAG, "bytes read for Asset file : " + isRead);
inputStream.close();
fileContent = new String(buffer);
} catch (IOException e) {
Log.e(LOG_TAG, "File read error = " + e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error on closing FileInputStream message = " + e.getMessage());
}
}
}
return fileContent;
}
Set Banner and Preference Center Logo
public OTConfiguration getOTConfiguration(@NonNull Context context) {
OTConfiguration.OTConfigurationBuilder otConfigurationBuilder = OTConfiguration.OTConfigurationBuilder.newInstance();
otConfigurationBuilder = otConfigurationBuilder.setBannerLogo(logo_location);
otConfigurationBuilder = otConfigurationBuilder.setPCLogo(logo_location);
OTConfiguration otConfig = otConfigurationBuilder.build()
}
// pass the otConfig instance as a param to the UI methods - showBannerUI()/setupUI()/showPreferenceCenterUI()
new OTPublishersHeadlessSDK(this).showBannerUI(RenderNativeUIActivity.this, otConfig);
Non-IAB TCF
Use the code reference below for a non-IAB implementation.
private void setOfflineData() throws JSONException {
JSONObject offlineData = new JSONObject();
String otData = readAssetFile(this, "ot_offline_domain_data.json");
if (!TextUtils.isEmpty(otData)) {
offlineData.put("otData", new JSONObject(otData));
}
new OTPublishersHeadlessSDK().setOTOfflineData(offlineData);
}
// Must call setOfflineData() first before startSDK()
setOfflineData()
startSDK()
IAB TCF
Use the code reference below for an IAB implementation.
private void setOfflineData() throws JSONException {
JSONObject offlineData = new JSONObject();
String otData = readAssetFile(this, "ot_offline_domain_data.json");
if (!TextUtils.isEmpty(otData)) {
offlineData.put("otData", new JSONObject(otData));
}
JSONObject vendorListData = new JSONObject();
String iabData = readAssetFile(this, "ot_offline_iab_data.json");
if (!TextUtils.isEmpty(iabData)) {
vendorListData.put("iabData", new JSONObject(iabData));
}
String googleData = readAssetFile(this, "ot_offline_google_data");
if (!TextUtils.isEmpty(googleData)) {
vendorListData.put("googleData", new JSONObject(googleData));
}
offlineData.put("vendorListData", vendorListData);
new OTPublishersHeadlessSDK().setOTOfflineData(offlineData);
}
// Must call setOfflineData() first before startSDK()
setOfflineData()
startSDK()
Capture Records of Consent
When a user provides consent, the SDK saves the data locally to the disk. It can also store a record of this consent on OneTrust servers. In order to enable this functionality, enable the Capture Records of Consent toggle in your geolocation rules. This will also allow data to be reflected for Dashboard reporting.
Cross Device Consent
Cross Device Consent is an optional feature. These parameters are not required for initializing the SDK.
If you are implementing the Cross Device Consent functionality, each of these OTProfileSyncParams
are required to be passed to the startSDK()
method to sync user profile data with OneTrust servers.
OTProfileSyncParams.OTProfileSyncParamsBuilder.newInstance()
.setSyncProfile("true")
.setSyncProfileAuth("JWT token")
.setIdentifier("userId")
.setIdentifierType("identifier type");
OTProfileSyncParams otProfileSyncParams = otProfileSyncParamsBuilder.build();
Parameter | Description | Required for Cross Device |
---|---|---|
setSyncProfile | Set to "true" to enable cross device profile syncing. | Yes |
setSyncProfileAuth | Sets the JWT to authenticate your request to fetch user profiles. | Yes |
setIdentifier | Sets the identifier value used to fetch or create a user profile server-side. | Yes |
setIdentifierType | Sets the identifier type for Unified Profile. | No, only when Unified Profile is in use |
For more information and best practices on Cross Device Consent, see Cross Domain and Cross Device Consent.
For implementation guidance on moving from an anonymous to known state, see Override Server Consent.
Updated about 15 hours ago