Welcome to the Axeptio Mobile SDK Samples project! This repository demonstrates how to implement the Axeptio Android SDK in your mobile applications.
- Overview
- Getting Started
- Local Testing with Production Widget Configuration
- Switching Between Publisher and Brand Flavors
- Axeptio SDK Implementation
- Initialize the SDK
- Responsibilities: Mobile App vs SDK
- Get Stored Consents
- Show Consent Popup on Demand
- Popup Events
- Event source for KPI tracking
- Sharing Consents with Other Web Views
- Clear User's Consent Choices
- Google Consent v2
- TCF Vendor Management APIs
This project includes two modules:
samplejava: Demonstrates how to use the Axeptio SDK with Java and XML.samplekotlin: Shows the integration of the Axeptio SDK with Kotlin and Compose, including advanced debugging features and configuration management.
Both modules can be built using either the brands or publishers variants, depending on your specific needs.
The samplekotlin module includes additional debugging and testing capabilities:
- Configuration Management: Dynamic switching between Brands and Publishers TCF services
- Debug Consent Info: Detailed analysis of TCF consent data and vendor information
- Vendor Consent Testing: Live testing interface for individual vendor consent validation
- Automation Scripts: Complete build, deploy, and testing automation
⚠️ Note: TheConfigurationManagerclass is part of the sample application and is not included in the Axeptio SDK. It demonstrates how to implement dynamic configuration switching in your own applications.
To begin testing the Axeptio SDK sample applications, follow these steps:
First, clone the repository to your local development environment:
git clone https://github.com/axeptio/sample-app-android🛡️ Maven requires authentication to access private repositories such as GitHub Packages. Without valid credentials (GitHub username and token), Gradle will not be able to download dependencies and will return a 401 Unauthorized error. The following steps explain how to create a Personal Access Token and configure Gradle to use it securely via environment variables.
To properly configure access to the Axeptio SDK, you need to add your GitHub token in the settings.gradle.kts file to fetch the SDK from the private repository. The library is not available on a public Maven repository, so it is crucial to configure the private repository correctly to avoid errors. You can also consider publishing the Axeptio SDK to a public repository to simplify integration, reducing the process complexity. Here’s how to configure the private repository in the settings.gradle.kts file:
maven {
url = uri("https://maven.pkg.github.com/axeptio/axeptio-android-sdk")
credentials {
username = "[GITHUB_USERNAME]" // Enter your GitHub username
password = "[GITHUB_TOKEN]" // Enter your GitHub token
}
}You can avoid hardcoding credentials by using environment variables instead of directly writing your GitHub username and token in the file. This is more secure and avoids leaking sensitive information.
To do this, replace the static strings with calls to environment variables using System.getenv() as follows:
credentials {
username = System.getenv("GITHUB_USERNAME")
password = System.getenv("GITHUB_TOKEN")
}If you haven't already created a GitHub Personal Access Token (PAT), you can do so by:
- Going here
- Clicking on "Generate new token (classic)"
- Giving it a name and expiration
- Selecting the
read:packagesscope - Generating and copying the token (you will not be able to see it again)
Once you have the token, export it as environment variables
- On macOS/Linux (e.g., in
.bashrc,.zshrc, or shell session):export GITHUB_USERNAME="your-github-username" export GITHUB_TOKEN="your-personal-access-token"
- On Windows (CMD):
setx GITHUB_USERNAME "your-github-username" setx GITHUB_TOKEN "your-personal-access-token"
After doing this, Gradle will automatically pick them up when resolving dependencies.
For local testing without real Google services
export GOOGLE_PROJECT="demo-project-12345"
export GOOGLE_API_KEY="AIzaSyDemoKey1234567890abcdefghijklmnop"and then run
./generate-config.shBefore proceeding with the integration, ensure that your project is correctly configured in the Axeptio backoffice. Specifically, verify that your clientId and configurationId are set up correctly. This is critical for the SDK to function as expected. If these values are not correctly configured, the SDK will not initialize properly, leading to errors during integration.
Choose the module corresponding to your preferred programming language and UI framework:
- samplejava: Java and XML integration
- samplekotlin: Kotlin and Compose integration
Depending on your use case, select the appropriate build variant:
- publishers
- brands
To test SDK changes using a cookie configuration from the production backoffice, follow these steps:
- Checkout the
axeptio-android-sdk-sourcesrepository and switch to the branch you need to test. - Configure the widget as described in the configuration section.
To test the version currently in production, instead checkout the sample-app-android repository, configure the widget, and in build.gradle.kts set the desired SDK version, for example:
implementation("io.axept.android:android-sdk:2.0.6")To configure the widget, update the productFlavors in build.gradle.kts with the appropriate AXEPTIO_CLIENT_ID, AXEPTIO_COOKIES_VERSION, and AXEPTIO_TARGET_SERVICE. Example:
productFlavors {
create("publishers") {
dimension = "service"
buildConfigField("String", "AXEPTIO_CLIENT_ID", "\"67b63ac7d81d22bf09c09e52\"")
buildConfigField("String", "AXEPTIO_COOKIES_VERSION", "\"tcf-consent-mode\"")
buildConfigField("String", "AXEPTIO_TARGET_SERVICE", "\"publishers\"")
}
create("brands") {
dimension = "service"
buildConfigField("String", "AXEPTIO_CLIENT_ID", "\"67f3f816b336596c4a7c741c\"")
buildConfigField("String", "AXEPTIO_COOKIES_VERSION", "\"demo-en-EU\"")
buildConfigField("String", "AXEPTIO_TARGET_SERVICE", "\"brands\"")
}
}Use the Build Variants tab to switch between brands and publishers as needed. Finally, make sure your settings.gradle.kts includes your GitHub credentials for accessing the SDK:
maven {
url = uri("https://maven.pkg.github.com/axeptio/axeptio-android-sdk")
credentials {
username = "USER" // TODO: GITHUB USERNAME
password = "TOKEN" // TODO: GITHUB TOKEN
}
}The Axeptio SDK provides two build flavors: publishers and brands. You can switch between them depending on your project needs. Each flavor activates specific behavior in the SDK.
- Locate the "Build Variants" tab (usually in the lower-left corner of the IDE).
- If it's not visible, go to View > Tool Windows > Build Variants to enable it.
- In the Module column, select either
publishersDebugorbrandsDebugfrom the dropdown.
Use Gradle commands to build a specific variant:
./gradlew assemblePublishersDebugor
./gradlew assembleBrandsDebugMake sure to clean the project if you switch flavors often:
./gradlew cleanThe Axeptio SDK provides consent management functionality for Android applications, enabling seamless integration for handling user consent.
The SDK is hosted on GitHub Packages and is compatible with Android SDK versions >= 26.
Follow these steps to integrate the Axeptio SDK into your Android project:
-
Add the Maven repository to your
settings.gradlefileEnsure the provided GitHub token has the
read:packagesscope enabled. Add the following configuration to yoursettings.gradlefile. -
Kotlin DSL
// Start dependency resolution management block
dependencyResolutionManagement {
repositories {
// Add Google's Maven repository to the project
google()
// Add Maven Central repository
mavenCentral()
// Add the GitHub Packages repository for the Axeptio SDK
maven {
// Set the URL of the GitHub repository hosting the Axeptio SDK
url = uri("https://maven.pkg.github.com/axeptio/axeptio-android-sdk")
// Configure credentials for accessing the GitHub Packages repository
credentials {
// Provide your GitHub username here
username = System.getenv("GITHUB_ACTOR")
// Provide your GitHub token here, ensuring the 'read:packages' scope is enabled
password = System.getenv("GITHUB_TOKEN")
}
}
}
}- Groovy
repositories {
maven {
url = uri("https://maven.pkg.github.com/axeptio/axeptio-android-sdk")
credentials {
username = "[GITHUB_USERNAME]"
password = "[GITHUB_TOKEN]"
}
}
}- Add the SDK dependency to your
build.gradlefile After adding the repository, include the Axeptio SDK as a dependency in your project. - Kotlin DSL
dependencies {
implementation("io.axept.android:android-sdk:2.0.6")
}- Groovy
dependencies {
implementation 'io.axept.android:android-sdk:2.0.6'
}For more detailed instructions, refer to the GitHub Documentation
To initialize the Axeptio SDK, you must call the initialization method inside the onCreate() method of your main activity. This call should be made before invoking any other Axeptio SDK functions. The SDK can be configured for either Publishers or Brands using the AxeptioService enum during initialization.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize the Axeptio SDK with the required configuration
AxeptioSDK.instance().initialize(
activity = this@MainActivity, // Context of the current activity
targetService = AxeptioService.PUBLISHERS_TCF, // Choose the target service: Publishers or Brands
clientId = "your_client_id", // Replace with your actual client ID
cookiesVersion = "your_cookies_version", // Specify the version of cookies management
token = "optional_consent_token" // Optional: Provide an existing consent token if available
)
}@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize the Axeptio SDK with the required configuration
Axeptio axeptio = AxeptioSDK.instance();
axeptio.initialize(
MainActivity.this, // Context of the current activity
AxeptioService.PUBLISHERS_TCF, // Choose the target service: Publishers or Brands
"your_project_id", // Replace with your actual project ID
"your_configuration_id", // Provide your configuration ID
"optional_consent_token" // Optional: Provide an existing consent token if available
);
}Once the SDK is initialized, the consent popup will automatically display if the user's consent is either expired or has not yet been registered. The SDK takes care of managing the consent state automatically.
For publishers, you can transfer a user's consent information by providing their Axeptio token. This token allows the SDK to automatically update the user's consent preferences in the SharedPreferences, following the TCFv2 (Transparency and Consent Framework) IAB (Interactive Advertising Bureau) specifications.
This error can occur during installation, typically due to issues with the APK or dependencies. The best solution is to perform a clean build to ensure that all libraries are properly integrated. To do so, execute the following command in your terminal:
./gradlew clean buildThis will clean the project and rebuild it, resolving any issues related to corrupted or improperly linked files. After completing the build, try reinstalling the app.
- Client ID and Configuration ID should be properly configured according to your specific project setup.
- The Axeptio token is optional, but it allows for better management of user consent states across different sessions.
- Always ensure that you check for SDK initialization before calling
initialize()to prevent multiple initializations that could cause crashes.
The integration of the Axeptio SDK into your mobile application involves clear delineation of responsibilities between the mobile app and the SDK itself. Below are the distinct roles for each in handling user consent and tracking.
- Event Handling and User Consent Updates:
- The app is responsible for handling SDK events such as user consent actions. Based on these events, the app must adjust its behavior accordingly, ensuring that user consent is respected across sessions.
-
Displaying the Consent Management Interface:
- The Axeptio SDK is responsible for rendering the user interface for the consent management platform (CMP) once triggered. It provides a customizable interface for users to give or revoke consent.
-
Storing and Managing User Consent Choices:
- The SDK securely stores and manages user consent choices, maintaining a persistent record that can be referenced throughout the app's lifecycle.
-
Sending Consent Status via APIs:
- The SDK facilitates communication of the user's consent status through APIs, allowing the app to be updated with the user’s preferences.
You can retrieve the consents stored by the Axeptio SDK in SharedPreferences. The following example demonstrates how to access these values within your app:
- Kotlin Examples
// Access SharedPreferences to retrieve stored consent values
val sharedPref = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
// Retrieve a specific consent value by key (replace "key" with the actual key you're using)
val consentValue = sharedPref.getString("key", "default_value")In this example, replace key with the actual key used to store consent information, and default_value with the value you want to return if no consent is found.
For more detailed information about the stored values, cookies, and how to handle them according to the Axeptio SDK, please refer to the Axeptio Documentation
You can trigger the consent popup to open on demand at any point in your application by using the following methods.
- Kotlin:
// Show the consent popup on demand
AxeptioSDK.instance().showConsentScreen(
activity = activity, // Pass the activity context
managePreferencesUseCase = true // Optional: Manages user preferences when the popup is shown
)- Java
// Show the consent popup on demand
AxeptioSDK.instance().showConsentScreen(
activity, // Pass the activity context
true // Optional: Manages user preferences when the popup is shown
);When the consent popup is closed, an event is triggered. You can listen for this event by setting an AxeptioEventListener.
- Kotlin:
// Set an event listener for when the consent popup is closed
AxeptioSDK.instance().setEventListener(object : AxeptioEventListener {
override fun onPopupClosedEvent() {
// Handle the event when the popup is closed
}
})- Java
// Set an event listener for when the consent popup is closed
AxeptioSDK.instance().setEventListener(new AxeptioEventListener() {
@Override
public void onPopupClosedEvent() {
super.onPopupClosedEvent();
// Handle the event when the popup is closed
}
});To ensure proper KPI attribution in the back office, the App SDK now adds a specific event_source value when emitting TCF events from the WebView.
sdk-app-tcf→ Used when TCF is loaded in a mobile app (via WebView)sdk-web-tcf→ Used when TCF is loaded on a websitesdk-app-brands→ Used when the brands widget is loaded in an appsdk-web→ Used for regular brands on the web
⚠️ This change ensures that events triggered from the App SDK are not incorrectly counted under Web KPIs.
No additional configuration is needed on your side if you are using the official SDK integration.
This feature is available exclusively for Publishers service.
The SDK provides a helper function to append the axeptio_token query parameter to any URL. You can either specify a custom user token or use the token currently stored in the SDK.
- Kotlin:
// Append the Axeptio token to a URL
AxeptioSDK.instance().appendAxeptioToken(
uri = Uri.parse("https://myurl.com"), // The URL to which you want to append the token
token = AxeptioSDK.instance().token ?: "" // Use the current token, or provide a custom one
)This will return: https://myurl.com?axeptio_token=[token]
To clear the user’s consent choices, you can use the following method. Please note that this operation is asynchronous, so you should use the AxeptioEventListener.onConsentCleared() method to be notified when the user’s consent choices have been cleared from SharedPreferences.
- Kotlin
// Clear the user's consent choices
AxeptioSDK.instance().clearConsents()You can listen for the consent clearance event with the following code:
// Set an event listener for when the consents are cleared
AxeptioSDK.instance().setEventListener(object : AxeptioEventListener {
override fun onConsentCleared() {
// Handle the event when consents are cleared
}
})This section describes how to integrate Google Consent Mode with the Axeptio SDK in your Android application.
Before proceeding, ensure that Firebase Analytics is integrated into your Android project.
When user consent is collected through your Consent Management Platform (CMP), the SDK will automatically set the IABTCF_EnableAdvertiserConsentMode key in the SharedPreferences_ to true.
The Axeptio SDK provides a callback method to listen for updates on Google Consent. These updates need to be mapped to the corresponding Firebase models. Once the consent statuses are mapped, you can update Firebase Analytics consent settings using the setConsent() method from Firebase Analytics.
// Set an event listener to listen for Google Consent Mode updates
AxeptioSDK.instance().setEventListener(object : AxeptioEventListener {
override fun onGoogleConsentModeUpdate(consentMap: Map<GoogleConsentType, GoogleConsentStatus>) {
// Map the Google consent types and statuses to Firebase consent types
val firebaseConsentMap = consentMap.entries.associate { (type, status) ->
val firebaseConsentType = when (type) {
GoogleConsentType.ANALYTICS_STORAGE -> ConsentType.ANALYTICS_STORAGE
GoogleConsentType.AD_STORAGE -> ConsentType.AD_STORAGE
GoogleConsentType.AD_USER_DATA -> ConsentType.AD_USER_DATA
GoogleConsentType.AD_PERSONALIZATION -> ConsentType.AD_PERSONALIZATION
}
val firebaseConsentStatus = when (status) {
GoogleConsentStatus.GRANTED -> ConsentStatus.GRANTED
GoogleConsentStatus.DENIED -> ConsentStatus.DENIED
}
firebaseConsentType to firebaseConsentStatus
}
// Update Firebase Analytics consent with the mapped consent statuses
Firebase.analytics.setConsent(firebaseConsentMap)
}
})// Set an event listener to listen for Google Consent Mode updates
AxeptioSDK.instance().setEventListener(new AxeptioEventListener() {
@Override
public void onGoogleConsentModeUpdate(@NonNull Map<GoogleConsentType, ? extends GoogleConsentStatus> consentMap) {
super.onGoogleConsentModeUpdate(consentMap);
// Prepare the Firebase consent map
Map<FirebaseAnalytics.ConsentType, FirebaseAnalytics.ConsentStatus> firebaseConsentMap = new HashMap<>();
// Map the Google consent types and statuses to Firebase consent types
for (Map.Entry<GoogleConsentType, ? extends GoogleConsentStatus> entry : consentMap.entrySet()) {
FirebaseAnalytics.ConsentType firebaseConsentType = null;
switch (entry.getKey()) {
case ANALYTICS_STORAGE:
firebaseConsentType = FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE;
break;
case AD_STORAGE:
firebaseConsentType = FirebaseAnalytics.ConsentType.AD_STORAGE;
break;
case AD_USER_DATA:
firebaseConsentType = FirebaseAnalytics.ConsentType.AD_USER_DATA;
break;
case AD_PERSONALIZATION:
firebaseConsentType = FirebaseAnalytics.ConsentType.AD_PERSONALIZATION;
break;
}
FirebaseAnalytics.ConsentStatus firebaseConsentStatus = null;
switch ((GoogleConsentStatus) entry.getValue()) {
case GRANTED:
firebaseConsentStatus = FirebaseAnalytics.ConsentStatus.GRANTED;
break;
case DENIED:
firebaseConsentStatus = FirebaseAnalytics.ConsentStatus.DENIED;
break;
}
// Add the consent status mapping to the Firebase consent map
if (firebaseConsentType != null && firebaseConsentStatus != null) {
firebaseConsentMap.put(firebaseConsentType, firebaseConsentStatus);
}
}
// Update Firebase Analytics with the mapped consent statuses
FirebaseAnalytics.getInstance(MainActivity.this).setConsent(firebaseConsentMap);
}
});- Integrate Firebase Analytics into your Android project.
- Use the provided listener
onGoogleConsentModeUpdate()to capture consent updates. - Map the Google Consent Types and Google Consent Statuses to Firebase Consent Types-.
- Use Firebase’s
setConsent()method to update the user’s consent status in Firebase Analytics.
By following these steps, you can ensure that Google Consent Mode is correctly integrated with your application, and Firebase Analytics receives the consent status updates accordingly.
The Axeptio SDK provides comprehensive APIs for managing vendor consent in TCF (Transparency and Consent Framework) mode. These APIs are exclusively available for Publishers using the TCF service and allow you to query individual vendor consent states, implement vendor-specific functionality, and maintain compliance with IAB TCF requirements.
Use these APIs when your app needs to:
- Query consent status for specific advertising vendors
- Implement vendor-specific data processing logic
- Debug consent collection issues in TCF mode
- Ensure compliance with specific vendor requirements
These APIs allow you to retrieve and analyze vendor consent information in TCF mode:
Returns a map of all vendor IDs with their consent status:
- Kotlin:
try {
val vendorConsents: Map<Int, Boolean> = AxeptioSDK.instance().getVendorConsents()
// vendorConsents contains: {755: true, 756: false, 757: true, ...}
vendorConsents.forEach { (vendorId, isConsented) ->
println("Vendor $vendorId: ${if (isConsented) "CONSENTED" else "REFUSED"}")
}
} catch (e: Exception) {
// Handle potential errors (e.g., SDK not initialized, no consent data)
Log.e("VendorConsents", "Error retrieving vendor consents: ${e.message}")
}Returns only the vendor IDs that have been consented to:
- Kotlin:
try {
val consentedVendors: List<Int> = AxeptioSDK.instance().getConsentedVendors()
// consentedVendors contains: [755, 757, 760, ...]
println("${consentedVendors.size} vendors have been consented to")
consentedVendors.forEach { vendorId ->
println("✅ Vendor $vendorId is consented")
}
} catch (e: Exception) {
Log.e("ConsentedVendors", "Error retrieving consented vendors: ${e.message}")
}Returns only the vendor IDs that have been refused:
- Kotlin:
try {
val refusedVendors: List<Int> = AxeptioSDK.instance().getRefusedVendors()
// refusedVendors contains: [756, 758, 759, ...]
println("${refusedVendors.size} vendors have been refused")
refusedVendors.forEach { vendorId ->
println("❌ Vendor $vendorId is refused")
}
} catch (e: Exception) {
Log.e("RefusedVendors", "Error retrieving refused vendors: ${e.message}")
}Check if a specific vendor has consent:
- Kotlin:
try {
val vendorId = 755 // Example vendor ID
val isConsented: Boolean = AxeptioSDK.instance().isVendorConsented(vendorId)
if (isConsented) {
println("✅ Vendor $vendorId has consent - proceed with data processing")
// Safe to process data with this vendor
} else {
println("❌ Vendor $vendorId does not have consent - skip data processing")
// Do not process data with this vendor
}
} catch (e: Exception) {
Log.e("VendorCheck", "Error checking vendor $vendorId: ${e.message}")
// Assume no consent on error for safety
}For debugging and detailed consent analysis:
Returns detailed consent information including TCF strings and raw data:
- Kotlin:
try {
val debugInfo: Map<String, Any?> = AxeptioSDK.instance().getConsentDebugInfo()
// Access common TCF fields
val tcfString = debugInfo["IABTCF_TCString"] as? String
val vendorConsents = debugInfo["IABTCF_VendorConsents"] as? String
val vendorLegitimateInterests = debugInfo["IABTCF_VendorLegitimateInterests"] as? String
println("TCF String: $tcfString")
println("Vendor Consents Bitstring: $vendorConsents")
println("Vendor Legitimate Interests: $vendorLegitimateInterests")
// Log all available debug fields
debugInfo.forEach { (key, value) ->
println("$key: $value")
}
} catch (e: Exception) {
Log.e("DebugInfo", "Error retrieving debug information: ${e.message}")
}-
Error Handling: Always wrap API calls in try-catch blocks as these APIs may throw exceptions if the SDK is not properly initialized or if no consent data is available.
-
TCF Service Requirement: These vendor APIs are exclusively for Publishers using the TCF service. When using the Brands service, these APIs will return empty results as vendor consent management is specific to the TCF framework.
-
Performance Considerations: Cache vendor consent results when possible, as parsing TCF data can be computationally intensive for large vendor lists.
-
Data Processing Logic: Use
isVendorConsented()in your data processing pipeline to ensure compliance:
fun processUserData(vendorId: Int, userData: UserData) {
if (AxeptioSDK.instance().isVendorConsented(vendorId)) {
// Proceed with data processing
sendDataToVendor(vendorId, userData)
} else {
// Skip processing for this vendor
Log.d("Compliance", "Skipping vendor $vendorId - no consent")
}
}- Initialization Check: Ensure the SDK is initialized before calling these APIs by checking that you have called the
initialize()method successfully before attempting to retrieve vendor consent data.
⚠️ Important Note: The TCF vendor consent APIs are available starting from SDK version 2.0.8 and are exclusively for Publishers using the TCF service. These APIs will return empty results when used with the Brands service, as vendor consent management is specific to the TCF framework.
For more detailed information, you can visit the Axeptio documentation.
We hope this guide helps you get started with the Axeptio Android SDK. Good luck with your integration, and thank you for choosing Axeptio!