# Integrating the Android SDK

This guide describes how to integrate the DT Exchange SDK into your Android project, which uses Maven Central for dependency management.

### Prerequisites <a href="#h_01jhmfkah3736e6qf8kntzcd1g" id="h_01jhmfkah3736e6qf8kntzcd1g"></a>

Android 4.4+ (API Level 19)

## Step 1: Integrating the SDK in your App

You can integrate the DT Exchange SDK using either Maven Central dependencies or a manual download.\
Select one of the following options:

* [Configuring Maven Central](#configuring-maven-central)
* [Manually Downloading the SDK](#manually-downloading-the-sdk)

### **Configuring Maven Central**

To add DT Maven repository and plugins to your Gradle build script:

1. Add the following to your app product-level `build.gradle` inside the repositories section.
2. At the root level `build.gradle` file, there are usually two repository sections - one for `buildscript` and one for `allprojects`. Add the entry in `allprojects`:

{% code title="Groovy" %}

```groovy
allprojects {
  repositories {
    // add this
    mavenCentral()
  }
  // ...
}
```

{% endcode %}

3. Add the following to the project app-level `gradle` file inside the `dependencies` section.

{% code title="Groovy" %}

```groovy
dependencies {
    // ...
    implementation "com.fyber:marketplace-sdk:8.4.4"
    // ...
}
```

{% endcode %}

### **Manually Downloading the SDK**

To download the DT Exchange Android SDK, click here:

<a href="https://cdn2.inner-active.mobi/fmp-sdk/files/FyberMarketplace-Android-v8.4.4.zip" class="button secondary" data-icon="arrow-down">Android DTX SDK 8.4.4</a>

1. Log in to the [DT Console](https://console.fyber.com/).
2. Copy the following files from the `Fyber Marketplace SDK` folder to your `project libs` folder.
   * For version 8.4.4:

     `fyber-marketplace-8.4.4.aar`
   * For version 8.1.0 and above (for Open Measurement support):

     `omsdk-android-1.5.4-release.aar`
3. Add the following repositories and dependencies to the project `build.gradle` file:

{% code title="Java" %}

```java
repositories {
    // ...
    // Add a flat dir repository
    flatDir {
       dirs 'libs'
    }
}

dependencies {
   // Add the marketplace AAR libraries
   implementation (name:"fyber-marketplace-8.4.4", ext:'aar')
   // add open measurement sdk - fyber marketplace 8.1.0 and above
   implementation (name:"omsdk-android-1.5.4-release", ext:'aar')
}
```

{% endcode %}

## Step 2: Integrating Google Play Services

DT recommends using Google Play Services to access your Google Advertising ID. This ID tracks your app's daily active users (DAU), and many ad campaigns require it. Without the ID, ad inventory is limited.

1. In the app-level `build.gradle` file, add the following dependencies:

{% code title="Groovy" %}

```groovy
dependencies  {
    implementation ('com.google.android.gms:play-services-base:Version#')
    // use only the ads identifier library
    implementation ('com.google.android.gms:play-services-ads-identifier:x.y.z')
    // or implementation ('com.google.android.gms:play-services-ads:x.y.z')
}
```

{% endcode %}

2. For apps targeting API Level 31 (Android 12) or higher, declare the Google Play Services permission in the `AndroidManifest.xml` file.\
   This step is required unless the app uses a recent Google Mobile Ads SDK version.

{% code title="XML" %}

```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
```

{% endcode %}

For further information about Google Advertising ID Restrictions, read the following:

### Google Advertising ID Restrictions

<details>

<summary><strong>Permission Required for Advertising ID</strong></summary>

Google Advertising ID (GAID) is a unique string identifier that anonymously identifies a device for advertising purposes. Google Play Services provides this Advertising ID and enables users to opt out of personalized ads in apps or reset their identifier. When a user resets their identifier, it can connect to a previous identifier.

In 2021, Google announced a behavior change for apps targeting [Android 13](https://support.google.com/googleplay/android-developer/answer/6048248) (API Level 33) and higher, a `AD_ID` permission is required. For more information, see [Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en).

To receive the Advertising ID, developers must add a new permission to the manifest file unless the app uses a recent version of the Google Mobile Ads SDK:

**XML**

{% code title="XML" %}

```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
```

{% endcode %}

Recent versions of the Google Mobile Ads SDK (play-services-ads v20.4.0 and higher, or play-services-ads-identifier v17.1.0 and higher) include this permission. If the app uses these SDKs, the AD\_ID permission from the SDK's library manifest merges with your app's main manifest by default, making the Advertising ID available.

For more information about Google Play Services, see [Set Up Google Play Services](https://developers.google.com/android/guides/setup).

</details>

## Step 3: Adding Permissions - Android Manifest File

1. Add the following mandatory permission to your `AndroidManifest.xml` file:

{% code title="Java" %}

```java
<uses-permission android:name="android.permission.INTERNET"/>
```

{% endcode %}

2. To enhance targeting capabilities, add these permissions:

{% code title="Java" %}

```java
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```

{% endcode %}

{% hint style="info" %}
The `ACCESS_NETWORK_STATE` permission differentiates WiFi from a cellular network.
{% endhint %}

## Step 4: Initializing the SDK

SDK initialization is mandatory because the DT SDK relies on the Console configuration for functionality. Without it, the SDK won't operate, and no ads will display. DT recommends performing this step during the app's initialization. Follow these steps to initialize the SDK.

### Google Play Families Ads API

To participate in the Google Play Families Ads program, run the following code to indicate if the user is a child:

{% code title="Java" %}

```java
InneractiveAdManager.currentAudienceIsAChild();
```

{% endcode %}

{% hint style="info" %}
Call this API once per app session before initializing the SDK. If the app doesn't contain the API, the user is not considered a child user by default.
{% endhint %}

After configuring your `AndroidManifest` file and preparing to request ads, initialize `InneractiveAdManager.initialize(context, <"appID">)`, and pass on your Activity or application context with the following code:

{% code title="Java" %}

```java
public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      InneractiveAdManager.initialize(this, "Enter_Your_DT-Exchange_AppID");
   }

   @Override
   protected void onDestroy() {
      if (isFinishing()) {
           //Optionally destroy the SDK after the activity has been destroyed
   InneractiveAdManager.destroy();
      }
   }
}
```

{% endcode %}

{% hint style="info" %}
Call `InneractiveAdManager.destroy()` when you no longer need the library to display more ads, as this release any resources used by the SDK.
{% endhint %}

{% hint style="success" %}
If you intend to destroy the library from within your activity's `onDestroy` method, ensure that the activity has finished.\
To adjust or debug the logging library level, see [DT Logging on Android](https://docs.digitalturbine.com/dt-exchange/publishers/sdk-configuration/integrating-the-android-sdk/dt-logging-on-android).
{% endhint %}

#### Locating the App ID

To locate the App ID on the DT Console:

1. From the [DT Console](https://console.fyber.com/), go to **Monetization→App Management**.\
   The **Apps dashboard** window appears.
2. Navigate to the required app.\
   The App ID appears below the app's name.

<div align="left" data-with-frame="true"><img src="https://content.gitbook.com/content/8KSLu5HNiyDWpvGRZh7B/blobs/sCwPK4ThBibHEfmf6LCl/21955837604380" alt=""></div>

### Initialization Callback

You can use the following initialization callback to `InneractiveAdManager` to monitor the SDK's initialization status:

{% code title="Java" %}

```java
InneractiveAdManager.initialize(context, appId, new OnFyberMarketplaceInitializedListener() {
           @Override
           public void onFyberMarketplaceInitialized(FyberInitStatus status) {
               // ...
           }
});
```

{% endcode %}

Valid values:

* `SUCCESSFULLY`: SDK initialized successfully.
* `FAILED_NO_KITS_DETECTED`: Only the `core` DT Exchange library detected. Check dependencies and add the `video-kit` and `mraid-kit`.
* `FAILED`: SDK failed to communicate with servers. Retry initialization.
* `INVALID_APP_ID`: Incorrect app ID. Verify configuration or contact support.

{% hint style="warning" %}
DT recommends not using the SDK or performing ad requests when the `FyberInitStatus` is `FAILED`. The SDK attempts to re-initialize itself internally when an ad request is executed, but the callback is not invoked in such cases.
{% endhint %}

### Passing a User ID to the SDK

To set a User ID for the SDK session, run the following code:

{% hint style="success" %}
The initial method of the SDK must be called in advance; there is no need to wait for the `onFyberMarketplaceInitialized` callback.
{% endhint %}

{% code title="Java" %}

```java
String userId = ...;
//Without reflection, using an import of the InneractiveAdManager class -
InneractiveAdManager.setUserId(userId);

//Optionally, using reflection as an example -
Class FyberInneractiveAdManagerClass =
    Class.forName("com.fyber.inneractive.sdk.external.InneractiveAdManager");
Method setUserIdStaticMethod =
    FyberInneractiveAdManagerClass.getDeclaredMethod("setUserId", String.class);
setUserIdStaticMethod.invoke(null, userId);
```

{% endcode %}

The basic Android SDK integration is complete. You can now integrate other ad types as required. For more information, see [Android Ad Formats](https://docs.digitalturbine.com/dt-exchange/publishers/sdk-configuration/integrating-the-android-sdk/android-ad-formats).

{% hint style="warning" %}
Review the instructions below for user consent related issues.
{% endhint %}

## Step 5: Adding User Consent

User consent mechanisms comply with various data protection laws. The following regulations mandate that users' data be handled with explicit consent:

* [GDPR](#01H8VGNGENZD5DAC75CXMWGZ8G)
* [CCPA](#01H8VGNGENHQ84WW6K15J0Q2M1)
* [LGPD](#01H8VGNGEPZVGRPFJAXJ3RRNKB)
* [COPPA](#01H8VGNGEPEAJ9ESSR1DT1WKMM)
* [GPP](#gpp)

### GDPR

The General Data Protection Regulation of the European Union ([GDPR](https://gdpr.eu/)) requires you to implement a user consent mechanism. A user is within the GDPR scope for your app when one or all of the following apply:

* The user is currently located in the EU.
* The user has registered with the app as an EU resident.
* The app is specifically targeted to EU users.

To comply with EU regulations and ensure seamless ad monetization, DT recommends consulting a legal advisor to determine the best approach for your business and using a Consent Management Platform (CMP).

If you haven’t updated to SDK 8.3.0 or later, you need to manually configure consent values with your CMP. The SDK automatically retrieves these values from 8.3.0 and later, eliminating the need for manual setup. For a complete list of CMPs, see the [Interactive Advertising Bureau - CMP List](https://iabeurope.eu/cmp-list/).

To incorporate GDPR consent values manually, set the `setGdprConsent` API in Boolean format, for example:

{% code title="Java" %}

```java
/**
     * Set the general data protection regulation user consent status
     * @param wasConsentGiven
     */
    public static void setGdprConsent(boolean wasConsentGiven) {…}

    // Calling the consent method

    InneractiveAdManager.setGdprConsent(true);

    /**
    * Set the general data protection regulation consent string
    * @param gdprConsent the consent string
    */
    public static void setGdprConsentString(String gdprConsent) {…}

    // Calling the consent method

    InneractiveAdManager.setGdprConsentString("consentString");
```

{% endcode %}

Valid values:

* `True`: The user grants consent.
* `False`: The user does not grant consent.

#### **Setting Consent String**

{% hint style="warning" %}
The user's consent status must be passed to the SDK before the SDK is initialized.\
When you set a GDPR consent value for a user, DT assumes that the user is subject to GDPR rules, even if the user is outside Europe. If a user updates their consent later, you only need to call the API again with the new value.
{% endhint %}

To set the GDPR consent string, use the following API:

{% code title="Java" %}

```java
InneractiveAdManager.setGdprConsentString("consentString");
```

{% endcode %}

To clear the consent flag and consent data, use the following API:

{% code title="Java" %}

```java
InneractiveAdManager.clearGdprConsentData();
```

{% endcode %}

If you don't obtain the user's consent before sending the SDK, only contextual ads appear.

### CCPA

The California Consumer Privacy Act of 2018 ([CCPA](https://iabtechlab.com/standards/ccpa/)) protects the personal information of California residents and applies to all companies operating in California. If a California resident uses a mobile app developer's app, CCPA applies to the developer and every company that processes the personal information of the app's users.

For more information on CCPA and DT's practices, see US Privacy Compliance and [IAB CCPA Compliance Framework](https://www.iab.com/guidelines/ccpa-framework/).

#### **CCPA API**

To set the CCPA consent string, use the following API:

{% code title="Java" %}

```java
/*** Setting the US privacy setting string
* @param consentString a non empty String
*/
public static void setUSPrivacyString(String consentString) {…}

// Calling the consent method
InneractiveAdManager.setUSPrivacyString("1YNN");
// This is an example value when the user chooses NOT to 'opt-out'
```

{% endcode %}

DT supports the following values for the US Privacy String:

* `1---`: CCPA does not apply, for example, the user is not a California resident.
* `1YNN`: User does NOT opt out, ad experience continues.
* `1YYN`: User opts out of targeted advertising.

For more information, see [IAB US Privacy String](https://github.com/InteractiveAdvertisingBureau/USPrivacy/blob/master/CCPA/US%20Privacy%20String.md).

To clear the privacy setting flag and opt-out data, use the following API:

{% code title="Java" %}

```java
InneractiveAdManager.clearUSPrivacyString();
```

{% endcode %}

### LGPD

The Brazilian General Data Protection Law, the Lei Geral de Proteção de Dados Pessoais ([LGPD](https://lgpd-brazil.info/)), mandates processing personal data for legitimate, specific, explicit, and communicated purposes.

To set the LGPD consent values, use the following API:

{% code title="Java" %}

```java
InneractiveAdManager.setLgpdConsent(boolean wasConsentGiven)
```

{% endcode %}

Valid values:

* `IALGPDConsentTypeGiven`: `True`.
* `IALGPDConsentTypeDenied`: `False`.

If the consent value is not set, the default is `False`.

### COPPA

The Children's Online Privacy Protection Act of 1998 ([COPPA](https://www.ftc.gov/legal-library/browse/rules/childrens-online-privacy-protection-rule-coppa)) is a federal law that imposes specific requirements on websites and online service operators to protect the privacy of children under 13.

#### COPPA API for Flagging Specific Users

Android SDK 8.2.3 and later supports the COPPA API, which allows publishers to flag specific end users as children as required under COPPA.

{% hint style="warning" %}
Execute the COPPA API after successfully initializing the DT SDK and after every successful SDK initialization
{% endhint %}

To confirm that the target audience of the application applies to COPPA, use the following API:

{% code title="Java" %}

```java
InneractiveAdManager.currentAudienceAppliesToCoppa();
```

{% endcode %}

{% hint style="info" %}
It is the publisher’s responsibility to decide whether to use the COPPA API or to treat all users as children.\
If you want flag all users as children, see [coppa](https://docs.digitalturbine.com/dt-exchange/publishers/getting-started-with-dt-exchange/privacy/coppa "mention").
{% endhint %}

### GPP

The IAB Global Privacy Protocol ([GPP](https://globalprivacyplatform.com/)) is a standardized framework for managing and transmitting user consent and privacy signals across the digital advertising ecosystem.

&#x20;GPP is supported starting with Android SDK 8.4.4. For more information, see [gpp](https://docs.digitalturbine.com/dt-exchange/publishers/getting-started-with-dt-exchange/privacy/gpp "mention").

## Step 6: Configure Parameters

To add gender and age parameters, use the following API:

{% code title="Java" %}

```java
// For gender values, see: InneractiveUserConfig.Gender
InneractiveAdManager.setUserParams(new InneractiveUserConfig()
        .setGender(InneractiveUserConfig.Gender.FEMALE));
```

{% endcode %}

## Step 7: app-ads.txt

The `app-ads.txt` standard helps prevent the unauthorized selling of in-app inventory and app domain spoofing.

For more information about how to list your Developer Website URL in the Google Play Store, see [Adding a Developer Website](https://docs.digitalturbine.com/dt-exchange/publishers/getting-started-with-dt-exchange/advanced-configurations/app-ads.txt).

## Step 8: (Optional ) Using the DT Exchange SDK in Secure Only Mode

The `InneractiveAdManager` API enables you to control how the SDK should perform any network connections.

{% code title="Java" %}

```java
InneractiveAdManager.useSecureConnections(boolean useSecureConnnections)
```

{% endcode %}

By invoking this setter with a value of `true`, all outgoing network connections from the DT Exchange SDK will use SSL/HTTPS. The default behavior is not to use secure connections.

{% hint style="warning" %}
Requesting secure-only content may decrease the demand that the SDK can render.
{% endhint %}

{% hint style="info" %}
The Android application-level secure API (`network-security-config cleartextTrafficPermitted`) takes precedence over this value. If you set `cleartextTrafficPermitted` to `false` and invoke the `useSecureConnections` setter with a value of `false`, the SDK behaves as if you requested secure connections only.
{% endhint %}
