> For the complete documentation index, see [llms.txt](https://docs.sfbx.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sfbx.io/configuration/step-3-notice-implementation-web-app-tv/android/unified-sdk/how-to-use-it.md).

# How to use it?

{% hint style="info" %}
**Reference in your IDE**\
This page lists the most commonly used methods. The exhaustive reference for the exact\
version you integrate ships with the dependency: in Android Studio, hover any SFBX or\
Appconsent member, or press Ctrl+Q (F1 on macOS), to read its documentation.
{% endhint %}

### Before use it: Set up your SDK

```kotlin
SFBX.initialize(
     configuration = Configuration(
          appkey = "YOUR APPKEY",
          optionals = emptyMap()
     ),
     onCmpReady = { appconsent ->
          // The SFBX AppConsent instance is ready to be used
     },
     onCmpOnError = {
          // Something went wrong
     },
)
```

First, set the `appkey` you retrieved from your dashboard in the `Configuration` object (see the previous step: [Get your appkey](https://docs.sfbx.io/configuration/step-3-notice-implementation-web-app-tv/android/unified-sdk/step-3-integration#id-1.-get-your-appkey)).\
\
Then define `onCmpReady`, the callback the SDK invokes once to notify you that it is ready to be used.

Finally, define `onCmpOnError`, the callback the SDK invokes if it encounters an error and cannot be used. If this happens, you have to call `SFBX.initialize(...)` again.

{% hint style="info" %}
The `optionals` field is currently a no-op.

You don't need to use it unless we explicitly tell you to. Its purpose is to let you enable recent features of our internal web SDK that are not yet exposed by the native SDK.

For more details, see the KDoc of the version you have integrated, directly in your IDE.
{% endhint %}

### Exceptions

| Exception                                   | When                                                                      | What to do                                         |
| ------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------- |
| AppConsentNotInitialized                    | SFBX.getInstance() before onCmpReady                                      | Wait for onCmpReady                                |
| AppConsentAppKeyNotDefined                  | appkey empty                                                              | Fix your Configuration                             |
| AppConsentAppKeyMalFormatted                | appkey malformed or unknown                                               | Check the key on your dashboard                    |
| AppConsentNoConnectivityException           | No network at all (airplane mode)                                         | Retry when a network is back                       |
| AppConsentWebviewError                      | System WebView missing, disabled or updating                              | Retry later; the SDK cannot work without it        |
| AppConsentSaveFailedException               | Our backend refused the consent save                                      | Inspect the message, retry                         |
| AppConsentCallbackJSOnError                 | The CMP engine reported an error                                          | Inspect the message, contact support if persistent |
| AppConsentConnectivityException             | The CMP was closed because the network was lost during a critical request | Let the user retry                                 |
| AppConsentUnhandledError, AppConsentOnError | Any other failure, see the cause                                          | Log it, contact support                            |

### **How to use Appconsent Instance?**

Here is a list of the most commonly used methods.

### Knowing whether the user has given consent

```kotlin
appconsent.isConsentGiven()
```

Returns `true` as soon as a consent choice is stored on the device, `false` if the user has not answered yet.

{% hint style="danger" %}
**WARNING**

This only tells you whether the user **has confirmed a choice**, not what the choice was: "Accept all", "Refuse all" and a custom selection all count as a given consent. It tells you whether the user still has to be asked, through presentNotice(). To know what was allowed, use `getConsentStatus()` or a granular method such as `isIabPurposeAllowed()`.
{% endhint %}

### CMP display modes

There are three display modes:

1. The first mode is **ONLY** executed if user consent is required.
2. The second mode allows your users to view/modify their consent with direct access to layer 1 (*often used from your settings screen to display your user's privacy policy*) - layer 1 corresponds to the main display of your notice. The window will be displayed **ALL THE TIME**.\
   ***This does not take into account the GDPR regulations of your users' geographic location.***
3. The last one is actually equivalent to the second one, except that the user has direct access to layer 2. This screen allows you to configure your different purposes/stacks in detail, as well as your partners. The window will be displayed **ALL THE TIME**.\
   ***This does not take into account the GDPR regulations of your users' geographic location.***

{% hint style="info" %}
**NOTE**

By default, this “**presentNotice**” method attempts to display the CMP. It attempts to do so because, depending on the region of your users, it will follow its controls and display the CMP only if necessary.\
\
It will also be displayed if user consent has not yet been given or if it needs to be renewed.
{% endhint %}

```kotlin
appconsent.presentNotice()  // Conditional — displays only if GDPR applies, and consent is missing or no longer valid
appconsent.displayLayer1()  // GDPR-agnostic — always displays the first consent layer
appconsent.displayLayer2()  // GDPR-agnostic — always displays the second consent layer
```

{% hint style="info" %}
When there is nothing to display, presentNotice() calls onCmpNotDisplayed(null):\
a null error means "consent already up to date", a non-null one means a failure.
{% endhint %}

### **GCM Status**

{% hint style="info" %}
**INFO**

This method shows the **current** status of GCMv2 (Google Consent Mode V2).

Before calling up this method, it's best to make sure that the user has **already given their consent** and that it's up to date, and that the CMP doesn't need to be redisplayed.

Otherwise :

* either the saved value of the **old consent** will be returned
* or the **default values** of your FirebaseAnalytics AndroidManifest configuration will be returned

[Set the default consent state from google documentation](https://developers.google.com/tag-platform/security/guides/app-consent?consentmode=advanced\&platform=android#default-consent)
{% endhint %}

```kotlin
appconsent.getGCMState()
```

Return `ACGcmState`

<details>

<summary>Data model representing the state of GCMv2 (Google Consent Mode v2)</summary>

This will allow you to define consent from your Firebase Analytics instance.

`isAnalyticsStorageGranted`, indicates whether the user has given consent for **FirebaseAnalytics.ConsentType#ANALYTICS\_STORAGE**

`isAdStorageGranted`, indicates whether the user has given consent for **FirebaseAnalytics.ConsentType#AD\_STORAGE**

`isAdUserDataGranted`, indicates whether the user has given consent for **FirebaseAnalytics.ConsentType#AD\_USER\_DATA**

`isAdPersonalizationGranted`, indicates whether the user has given consent for **FirebaseAnalytics.ConsentType#AD\_PERSONALIZATION**

[FirebaseAnalytics.ConsentType](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.ConsentType)

</details>

### **Check for update**

This method allows you to check from our servers whether your Notice has been updated since it was last displayed on your user's device.

{% hint style="info" %}
**INFO**&#x20;

The method will return true if you have modified the Source and/or Notice from your dashboard and, if and **only if**, you have configured your Notice to update for all your users.
{% endhint %}

<figure><img src="https://4229351976-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FkyFlZKFaKP4MUM0zILOg%2Fuploads%2Fr0pByhnZyUtDmk5qVLRD%2Fcheck_for_update_notice.png?alt=media&amp;token=37298ec4-ac21-4c66-8914-69911b1c43ae" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
**ATTENTION**

The answer of our backend is cached for 30 minutes. Within that window, every call\
reuses the cached answer; a network call is attempted again only if the previous one\
failed. This cache is shared with presentNotice() and displayLayer1(), which perform\
the same check before displaying: right after you update your Notice, a device that\
got a "no update" answer less than 30 minutes ago will not display the CMP yet.
{% endhint %}

```kotlin
appconsent.checkForUpdate({ needToUpdate: Boolean ->
    if (needToUpdate) {
        /*
         The Notice has been updated and must be resubmitted to your users.

         Nothing else to do here: let your app's usual consent checkpoint call
         presentNotice(), as set up earlier in your app lifecycle. presentNotice()
         collects the consent again, under the SAME user identifier, and the answer
         you just received is cached, so it displays the notice right away.

         Do not call presentNotice() directly from this callback: redirect the user
         to the screen of your app where the CMP is displayed as part of the normal
         user journey.
         */
    } else {
        /*
         The Notice has not changed since the last verification: no changes on your
         end, no internal update (such as a vendor list update). No action required.
         */
    }
}) { appconsentExceptions: AppconsentExceptions ->
    // An error occurred while checking for Notice updates.
}
```

## Using AppConsent's more specific methods

Here's a list of methods that could be useful if you want to go further in tracking user consent.

### **IAB Purpose X Allowed**

```kotlin
appconsent.isIabPurposeAllowed(1)
```

Returns `true` if the purpose with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabId` of your purpose.

### IAB Purposes Allowed

```kotlin
appconsent.iabPurposeIdsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** purposes **ONLY**.

### **IAB Feature X Allowed**

```kotlin
appconsent.isIabFeatureAllowed(1)
```

Returns `true` if the feature with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabFeatureId` of your feature.

### IAB Features Allowed

```kotlin
appconsent.iabFeatureIdsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** features **ONLY**.

### **IAB Special Feature X Allowed**

```kotlin
appconsent.isIabSpecialFeatureAllowed(1)
```

Returns `true` if the special feature with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabSpecialFeatureId` of your special feature.

### IAB Special Features Allowed

```kotlin
appconsent.iabSpecialFeatureIdsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** special features **ONLY**.

### **IAB Special Purpose X Allowed**

```kotlin
appconsent.isIabSpecialPurposeAllowed(1)
```

Returns `true` if the special purpose with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabSpecialPurposeId` of your special purpose.

### IAB Special Purposes Allowed

```kotlin
appconsent.iabSpecialPurposeIdsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** special purposes **ONLY**.

### **Stack X Allowed**

```kotlin
appconsent.isIabStacksAllowed(1)
```

Returns `true` if the stack with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabStackId` of your stack.

### IAB Stacks Allowed

```kotlin
appconsent.iabStacksIdsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** stack **ONLY**.

### **Vendor X Allowed**

```kotlin
appconsent.isIabVendorAllowed(1)
```

Returns `true` if the vendor with `id = 1` is authorized, `false` otherwise. The `id` to pass is the `iabVendorId` of your vendor.

### IAB Vendors Allowed

```kotlin
appconsent.iabVendorsAllowed() : List<Int>
```

Returns a list of integers representing the IDs of **accepted** vendors **ONLY**.

### **Extra Vendor X Allowed**

```kotlin
appconsent.isExtraVendorAllowed("abc123")
```

Returns `true` if the extra vendor with `id = "abc123"` is authorized, `false` otherwise.

### Extra Vendors **Allowed**

```kotlin
appconsent.extraVendorsAllowed() : List<String>
```

Returns a list of string representing the IDs of **accepted** extra vendors **ONLY**.

### **Extra Purpose X Allowed**

```kotlin
appconsent.isExtraPurposeAllowed("abc123")
```

Returns `true` if the extra purpose with `id = "abc123"` is authorized, `false` otherwise.

### Extra Purposes Allowed

```kotlin
appconsent.extraPurposeIdsAllowed() : List<String>
```

Returns a list of string representing the IDs of **accepted** extra purpose **ONLY**.

### Purposes list

```kotlin
appconsent.getPurposes() : List<ACConsentable>
```

Returns a list of all purposes in your source with the user-defined status `ACConsentable`.

```kotlin
data class ACConsentable(
    override val id: String,
    override val type: String,
    override val status: String,
    override val additionalInfo: Map<String, String>,
)
```

* `id`: the identifier of the purpose.
* `type`: the kind of consentable item, here `PURPOSE`.
* `status`: the user's choice, as an integer in string form (see `ACConsentableStatus`).
* `additionalInfo`: reserved for extra attributes the IAB may introduce, so that new\
  information can be exposed without changing this model.

### Purposes list by status

```kotlin
appconsent.getPurposesByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all purposes in your source filtered by the status you pass as a parameter.

### Features list

```kotlin
appconsent.getFeatures() : List<ACConsentable>
```

Returns a list of all features in your source with the user-defined status `ACConsentable`.

### Features list by status

```kotlin
appconsent.getFeaturesByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all features in your source filtered by the status you pass as a parameter.

### Special Purpose list

```kotlin
appconsent.getSpecialPurposes() : List<ACConsentable>
```

Returns a list of all special purposes in your source with the user-defined status `ACConsentable`.

### Special Purpose list by status

```kotlin
appconsent.getSpecialPurposesByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all special purposes in your source filtered by the status you pass as a parameter.

### Special Feature list

```kotlin
appconsent.getSpecialFeatures() : List<ACConsentable>
```

Returns a list of all special features in your source with the user-defined status `ACConsentable`.

### Special Feature list by status

```kotlin
appconsent.getSpecialFeaturesByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all special features in your source filtered by the status you pass as a parameter.

### Extra Purpose list

```kotlin
appconsent.getExtraPurposes() : List<ACConsentable>
```

Returns a list of all extra purpose in your source with the user-defined status `ACConsentable`.

### Extra Purpose list by status

```kotlin
appconsent.getExtraPurposesByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all extra purpose in your source filtered by the status you pass as a parameter.

### Stack list

```kotlin
appconsent.getStacks() : List<ACConsentable>
```

Returns a list of all stack in your source with the user-defined status `ACConsentable`.

### Stack list by status

```kotlin
appconsent.getStacksByStatus(status: ACConsentableStatus) : List<ACConsentable>
```

Returns a list of all stack in your source filtered by the status you pass as a parameter.

### Extra Vendors list

```kotlin
appconsent.getExtraVendors() : List<ACExtraVendor>
```

Returns a list of all extra vendors in your source with the user-defined status `ACExtraVendor`.

```kotlin
data class ACExtraVendor(
    override val id: String,
    override val type: String,
    override val status: String,
    override val additionalInfo: Map<String, String>,
)
```

### Extra Vendors list by status

```kotlin
appconsent.getExtraVendorsByStatus(status: ACConsentableStatus) : List<ACExtraVendor>
```

Returns a list of all extra vendors in your source filtered by the status you pass as a parameter.

### Is the user's consent mixed?

```kotlin
appconsent.isConsentMixed()
```

Returns `true` if some consent items have been accepted and others rejected.

### Did the user accept everything?

```kotlin
appConsent.isAllAllowed()
```

Returns `true` if all consentables, stacks, and vendors are accepted. Returns `false` if at least one of them is not accepted.

### Did the user refuse everything?

```kotlin
appConsent.isAllDisallowed()
```

Returns `true` if all consentables, stacks, and vendors are rejected. Returns `false` if at least one of them is not rejected.

### Define the status of consentable items

```kotlin
appconsent.setConsentableConsents(
    newConsentableConsents: ACConsentOverride,
    onSuccess: () -> Unit,
    onError: (appconsentExceptions : AppconsentExceptions) -> Unit,
)
```

Define the status of the new consent and save it.

The `ACConsentOverride` object allows you to modify any consentable item as many times as you want in a single operation. It exposes seven optional lists: purposes, specialPurposes, extraPurposes, features, specialFeatures, vendors and extraVendors. Stacks cannot be overridden directly: set their purposes instead.

Each status is constructed in the following form using the `ACConsentStatus` object.\
The latter takes the following parameters:

* **id**: The ID of the consentable you want to modify (as a string)
* **status**: the new status you want to “redefine” (as a boolean)
  * `true`: **ALLOWED**
  * `false`: **DISALLOWED**
* **legintStatus**: the new legitimate status you want to “redefine” (as a boolean)
  * `true`: **ALLOWED**
  * `false`: **DISALLOWED**

`onSuccess`**:** is the callback that will be called if consent has been successfully modified and saved

`onError`**:** is the callback that will be called if an error occurred during the modification

### **Delete the consent**

{% hint style="danger" %}
**Destructive. This method DELETES the local consent AND ASSIGNS A NEW USER IDENTIFIER.**

The user's consent history is left behind on the previous identifier and can never be reattached. Do not call it in the normal life of your application. `presentNotice()` already collects the consent again, under the **same** identifier, whenever the CMP decides it is needed.

Reserve this method for an explicit user request to start over (*for example a "reset my consent and identity" action in your settings screen*), or for your own test builds.
{% endhint %}

```kotlin
appConsent.askToClearConsent(
    onSuccess: () -> Unit,
    onError: (appconsentExceptions : AppconsentExceptions) -> Unit,
)
```

{% hint style="info" %}
This action is asynchronous and requires an active network connection: without network, `onError` is invoked and nothing is cleared.
{% endhint %}

It deletes all locally stored consent information for the user (choices for vendors and purposes, the `IABTCF_*` keys, etc.). After the call, the SDK considers the user as not having provided consent yet: `isConsentGiven()` returns `false`. On the next `presentNotice()`, the CMP decides by itself whether the notice has to be shown: nothing is shown, for example, to a user outside the GDPR scope.

A **new user identifier** is generated by this call: the previous consent stays attached to the previous identifier on our servers, so the user starts over with a fresh identity. Google Consent Mode values go back to the defaults declared in your `AndroidManifest`.

{% hint style="info" %}
**@param** onSuccess A callback invoked upon successful update.\
**@param** onError A callback invoked if the update fails.
{% endhint %}

### Define your external IDs

```kotlin
val ids = mapOf<String, String>("customPersonalId" to "abze23", "otherData" to "{\"name\": \"test\"}")
appConsent.askToSetExternalIds(
    externalIds = ids,
    onSuccess = { },
    onError = { appconsentExceptions -> }
)
```

Sends your external IDs to our servers and attaches them to the user's consent identifier.

The map is sent **as is**: your keys replace the ones previously sent, a key missing from the map is no longer sent.

{% hint style="info" %}
This call does not update the local copy returned by `getLocalExternalIds()`. If you need the local copy and the server in sync, use `setLocalExternalIds()` followed by `saveExternalIds()` or `saveExternalIdsFromAPI()`.
{% endhint %}

### Retrieve your external IDs

Retrieve your previously saved external IDs

```kotlin
appConsent.askToGetExternalIds(
    onSuccess = { externalIds -> },
    onError = { appconsentExceptions -> }
)
```

### Define your external IDs locally

```kotlin
val ids = mapOf<String, String>("customPersonalId" to "abze23", "otherData" to "{\"name\": \"test\"}")
appConsent.setLocalExternalIds(
    externalIds = ids
)
```

Saves your external IDs **locally** only.

{% hint style="danger" %}
**This method REPLACES every external ID already stored on the device with the given map.** A key missing from the map is removed. To add an entry, read `getLocalExternalIds()` first and merge.
{% endhint %}

To synchronize the local IDs with our servers, call `saveExternalIdsFromAPI()` afterwards.

### Retrieve your local external IDs

```kotlin
appConsent.getLocalExternalIds() : Map<String, String>
```

Retrieve your externally saved IDs locally

### Get User ID

```kotlin
appconsent.getUserId() : String
```

Retrieves the Appconsent user identifier the consent is attached to on our servers.

### Find out if the user has restricted the use of their advertising ID

```kotlin
appconsent.isLimitedTrackingEnabled() : Boolean
```

`true` if the user ID is restricted, `false` otherwise

### Knowing if your user is subject to consent

```kotlin
appconsent.isSubjectToGDPR() : Boolean?
```

Returns `true` if your user is subject to consent, `false` if the user is not, `null` if the information is not yet known by our SDK.

### Know the overall status of purposes

```kotlin
appconsent.getPurposesStatus() : ACConsentableStatus
```

Allows you to quickly see the status of all purposes for your source, following user consent.

```kotlin
enum class ACConsentableStatus{
    DISALLOWED,
    PENDING,
    ALLOWED,
    MIXED,
    UNKNOWN,
}
```

### Know the overall status of stacks

```kotlin
appconsent.getStacksStatus() : ACConsentableStatus
```

Allows you to quickly see the status of all stacks for your source, following user consent.

### Know the overall status of vendors

```kotlin
appconsent.getVendorsStatus() : ACConsentableStatus
```

Allows you to quickly see the status of all vendors for your source, following user consent.

### Know the overall status of user's consent

```kotlin
appconsent.getConsentStatus() : ACConsentableStatus
```

Provides a quick overview of the status of user consent.

Quickly see whether the user has **ACCEPTED ALL**, **REFUSED ALL**, **MIXED**, **PENDING**, or **UNKNOWN**.

### Define user consent to REFUSE ALL

```kotlin
appconsent.forceDenyAll(onSuccess: () -> Unit, onError: (appconsentExceptions : AppconsentExceptions) -> Unit)
```

Allows you to confirm the “**DECLINE ALL**” action. This action behaves in the same way as if the CMP were displayed to your users and they clicked on the “**decline all**” button.

A new consent will be applied and saved.

### Define user consent to ACCEPT ALL

```kotlin
appconsent.forceAcceptAll(onSuccess: () -> Unit, onError: (appconsentExceptions : AppconsentExceptions) -> Unit)
```

Allows you to validate the “**ACCEPT ALL**” action. This action behaves in the same way as if the CMP were displayed to your users and they clicked on the “**accept all**” button.

A new consent will be applied and saved.

### Save your floating purpose

```kotlin
appconsent.saveFloatingPurpose(
    floatingPurposesStatus: Map<String, Boolean>,
    onSuccess: () -> Unit,
    onError: (appconsentExceptions : AppconsentExceptions) -> Unit
)
```

If you have defined floating purposes in your source, define their identifiers and user statuses as parameters so that they are taken into account and saved.

#### Find out if a floating purpose needs to be updated

```kotlin
appconsent.isFloatingNeedUpdate(                                                                                                                                          
    floatingPurposeId: String,                                                                                                                                            
    onSuccess: (isFloatingNeedToUpdate: Boolean) -> Unit,                                                                                                                 
    onError: (appconsentExceptions: AppconsentExceptions) -> Unit                                                                                                         
)                                                                                                                                                                         
```

If you have defined floating purposes in your source, this method checks whether the\
floating purpose passed as a parameter has been updated since the user's choice for it\
was last saved.

* `floatingPurposeId`: the identifier of the floating purpose, as defined in your source.
* `onSuccess`: invoked with `true` if the floating purpose has changed and the user's\
  choice must be collected again (then call `saveFloatingPurpose(...)` with the new\
  status), `false` if the saved choice is still valid.
* `onError`: invoked if the check could not be performed (for example without network).

### Forces the saving of your external credentials

#### Save your external IDs <a href="#toc_8" id="toc_8"></a>

```kotlin
appconsent.saveExternalIds(
    onSuccess: () -> Unit,
    onError: (appconsentExceptions : AppconsentExceptions) -> Unit
)
```

Saves to our servers the external IDs known to the CMP engine: the ones sent with askToSetExternalIds(), and the ones stored on the device when the SDK was initialized.

### Save your external IDs through the REST API

```kotlin
appconsent.saveExternalIdsFromAPI(
    onSuccess: () -> Unit,
    onError: (appconsentExceptions : AppconsentExceptions) -> Unit
)
```

Saves to our servers the external IDs stored on the device, including the ones you have just set with setLocalExternalIds(), through a direct REST call. This is the\
method to call after setLocalExternalIds().

## AppConsent(Bonus) Retrieve your consents

Your consents are saved in `SharedPreferences` of your application. To know more about keys used to save your consents, please refer to the [**IAB documentation**](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20CMP%20API%20v2.md#in-app-details).

We also store the Google Additional Consent string under the `IABTCF_AddtlConsent` key\
(*type `String`, for example `2~20.43.46~dv.`*).
