# Unity Bridge SDK Implementation Guide

This guide provides a comprehensive step-by-step process for integrating the Unity Bridge AdSter SDK into your Unity Android application.

{% hint style="info" %}
**App Prerequisite**

* minSdkVersion of 21 or higher
* compileSdkVersion of 34
  {% endhint %}

Android API level is set in **Project Settings > Player > Android > Other Settings > Other Settings**.

{% tabs %}
{% tab title="Android" %}
Go to **Project Settings > Player > Android > Publishing Settings > Build** and select:

* Custom Main Manifest Template
* Custom Main Gradle Template

<figure><img src="/files/3Q1A8qoPuwt5na8NoY1V" alt="" width="563"><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

## Configuration Steps

**Adding Dependency**

* Open the `mainTemplate.gradle` file.
* Find the dependencies block and add the following SDK dependency.

```groovy
implementation 'com.adstertech:orchestrationsdk-unity-bridge:2.6.6'
```

***

Use the below link to download the file and add AdsterBridgeUtil.cs in `Assets > Scripts`in your unity project.&#x20;

```url
https://storage.googleapis.com/adster-unity-bridge-docs/AdsterBridgeUtil.cs
```

#### AndroidManifest.xml

Add the below code inside the androidmanifest.xml file.

```xml
<activity android:name="com.adster.adsterunitybridge.unitybridge.CustomUnityPlayerActivity"
                  android:label="@string/app_name"
                  android:exported="true"
                  android:theme="@style/UnityThemeSelector">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>

```


# Initialising the SDK

{% tabs %}
{% tab title="C#" %}

```csharp
// Initialize the SDK
AdsterBridgeUtil.InitSdk("gameobject_name_goes_here");

//Callback to receive initialization status
private void OnInitializationComplete(string statusJson)
    {
        Debug.Log("SDK Initialized: " + statusJson);
    }
```

{% endtab %}
{% endtabs %}


# Banner Ad

Below are the steps to load and render a banner Ad on your app

Before loading ads, have your app initialize Adster Unity Bridge SDK.\
This needs to be done only once, ideally at app launch.

1. Call `LoadBannerAd()`method as per below format

```csharp
AdsterBridgeUtil.LoadBannerAd("Your_placement_name", "gameobject_name_goes_here", 
AdsterBridgeUtil.AdPosition.TOP_CENTER);
```

2. Declare `OnBannerAdEventReceived()` method as per below format

{% tabs %}
{% tab title="C#" %}

```java
private void OnBannerAdEventReceived(string message)
    {
        if (message == "AdLoaded")
        {
            Debug.Log("Banner ad loaded");
        }
        else if (message.StartsWith("AdFailed:"))
        {
            string error = message.Substring("AdFailed:".Length);
            Debug.LogError($"Failed to load banner ad: {error}");
        }
        else if (message.StartsWith("AdRevenuePaid"))
        {
            Debug.Log(message);
            string[] parts = message.Split('|');
            if (parts.Length == 4)
            {
                string revenue = parts[1];
                string adUnit = parts[2];
                string network = parts[3];
                Debug.Log($"[AdRevenue] Revenue: {revenue}, AdUnit: {adUnit}, Network: {network}");
            
            return;
            }
        }
    }
```

{% endtab %}
{% endtabs %}

3. Call below code when activity/fragment/scene is destroyed or detached.

```csharp
AdsterBridgeUtil.DestroyBannerAd();
```


# Interstitial Ad

Below are the steps to load and show an Interstitial ad on your app

Before loading ads, have your app initialize Adster Unity Bridge SDK.\
This needs to be done only once, ideally at app launch.

1. Call `LoadInterstitialAd()`method as per below format

<pre class="language-csharp"><code class="lang-csharp"><strong>AdsterBridgeUtil.LoadInterstitialAd("Your_placement_name", "gameobject_name_goes_here");
</strong></code></pre>

2. Declare `OnInterstitialAdEvent()` method as per below format

{% tabs %}
{% tab title="C#" %}

```csharp
public void OnInterstitialAdEvent(string message)
    {
        // Process ad events based on the message
        if (message == "AdLoaded")
        {
            Debug.Log("Interstitial ad successfully loaded.");
        }
        else if (message.StartsWith("AdFailed:"))
        {
            string error = message.Substring("AdFailed:".Length);
            Debug.LogError($"Failed to load interstitial ad: {error}");
        }
        else if (message == "AdOpened")
        {
            Debug.Log("Interstitial ad opened.");
        }
        else if (message == "AdClosed")
        {
            Debug.Log("Interstitial ad closed.");
        }
        else if (message == "AdClicked")
        {
            Debug.Log("Interstitial ad clicked.");
        }
        else if (message == "AdImpression")
        {
            Debug.Log("Interstitial ad impression recorded.");
        }
        else if (message.StartsWith("AdRevenuePaid"))
        {
            Debug.Log(message);
            string[] parts = message.Split('|');
            if (parts.Length == 4)
            {
                string revenue = parts[1];
                string adUnit = parts[2];
                string network = parts[3];
                Debug.Log($"[AdRevenue] Revenue: {revenue}, AdUnit: {adUnit}, Network: {network}");
            
            return;
            }
        }
    }
```

{% endtab %}
{% endtabs %}

3. Inside the `AdLoaded` callback method invoke `ShowInterstitialAd()` method as below to show AdSter interstitial ad above any scene/view.

{% tabs %}
{% tab title="C#" %}

```csharp
AdsterBridgeUtil.ShowInterstitialAd("gameobject_name_goes_here");
```

{% endtab %}
{% endtabs %}


# Rewarded Ad

Below are the steps to load and show a rewarded ad on your app

Before loading ads, have your app initialize Adster Unity Bridge SDK.\
This needs to be done only once, ideally at app launch.

1. Call `LoadRewardedAd()`method as per below format

```csharp
AdsterBridgeUtil.LoadRewardedAd("Your_placement_name", "gameobject_name_goes_here");
```

2. Declare `OnRewardedAdEvent()` method as per below format

{% tabs %}
{% tab title="C#" %}

```java
public void OnRewardedAdEvent(string message)
    {
        switch (message)
        {
            case "AdLoaded":
                Debug.Log("Rewarded ad loaded.");
                // Trigger any Unity logic for ad loaded here
                break;

            case "VideoStart":
                Debug.Log("Rewarded ad video started.");
                // Handle video start logic
                break;

            case "VideoClosed":
                Debug.Log("Rewarded ad video closed.");
                // Handle video closed logic
                break;

            case "VideoComplete":
                Debug.Log("Rewarded ad video completed.");
                // Handle video completion logic
                break;

            case "AdImpression":
                Debug.Log("Rewarded ad impression recorded.");
                // Handle ad impression logic
                break;

            case "AdClicked":
                Debug.Log("Rewarded ad clicked.");
                // Handle ad click logic
                break;

            default:
                if (message.StartsWith("RewardEarned:"))
                {
                    // Parse reward type and amount from the message
                    string[] rewardData = message.Substring("RewardEarned:".Length).Split(':');
                    string rewardAmount = rewardData[0];
                    Debug.Log($"User earned reward: Amount = {rewardAmount}");
                }
                else if (message.StartsWith("AdFailed:"))
                {
                    string error = message.Substring("AdFailed:".Length);
                    Debug.LogError($"Rewarded ad failed to load: {error}");
                }
                else if (message.StartsWith("AdRevenuePaid"))
                {
                    Debug.Log(message);
                    string[] parts = message.Split('|');
                    if (parts.Length == 4)
                    {
                        string revenue = parts[1];
                        string adUnit = parts[2];
                        string network = parts[3];
                        Debug.Log($"[AdRevenue] Revenue: {revenue}, AdUnit: {adUnit}, Network: {network}");
            
                    return;
                    }
                }
                break;
        }
    }
```

{% endtab %}
{% endtabs %}

3. Inside the `AdLoaded` callback method invoke `ShowRewardedAd()` method as below to show AdSter rewarded ad above any scene/view.

{% tabs %}
{% tab title="C#" %}

```csharp
AdsterBridgeUtil.ShowRewardedAd("gameobject_name_goes_here");
```

{% endtab %}
{% endtabs %}


# Native Ad

Below are the steps to load and show a native ad on your app

1. Create your `AdRequestConfiguration` as per the below format

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

2. Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onNativeAdLoaded(@NonNull MediationNativeAd ad) {
        super.onNativeAdLoaded(ad);
        //Show native ad here
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {    
    override fun onNativeAdLoaded(ad: MediationNativeAd) {
        super.onNativeAdLoaded(ad)
        //Show native ad here
    }

    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }

    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onNativeAdLoaded` callback method use `MediationNativeAd` object to display native ad on your defined layout.
4. Define your native ad layout, below is just an example of a layout

{% code overflow="wrap" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <!-- Choice Logo -->
    <ImageView
        android:id="@+id/choiceImageview"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="10"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <!-- Media View -->
        <FrameLayout
            android:id="@+id/mediaView"
            android:layout_width="0dp"
            android:layout_height="160dp"
            android:layout_weight="6" />

        <LinearLayout
            android:id="@+id/textLayout"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="16dp"
            android:layout_weight="4"
            android:orientation="vertical">

            <!-- Title -->
            <TextView
                android:id="@+id/titleTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="Sample Title"
                android:textColor="@color/black"
                android:textSize="16sp"
                android:textStyle="bold"
                android:visibility="gone"
                tools:visibility="visible" />

            <!-- Body -->
            <TextView
                android:id="@+id/bodyTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="Sample Body Text"
                android:textColor="@color/black"
                android:textSize="14sp"
                android:visibility="gone"
                tools:visibility="visible" />

            <!-- Info -->
            <TextView
                android:id="@+id/infoTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@color/black"
                android:textSize="12sp"
                android:visibility="gone"
                tools:text="Sample Advertiser Text"
                tools:visibility="visible" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <!-- Icon Logo -->
                <ImageView
                    android:id="@+id/iconLogoImageView"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:scaleType="centerInside" />

                <!-- Rating Bar -->
                <RatingBar
                    android:id="@+id/ratingBar"
                    style="@style/Widget.AppCompat.RatingBar.Small"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:lines="1"
                    android:numStars="5"
                    android:stepSize="0.1" />
            </LinearLayout>

            <!-- CTA Button -->
            <Button
                android:id="@+id/ctaButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="Learn More" />
        </LinearLayout>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
```

{% endcode %}

5. The above sample layout can be used with the `MediationNativeAd` object to render an ad as shown in the below example

{% tabs %}
{% tab title="Java" %}

```java
private void displayNativeAd(MediationNativeAd ad) {
  // Create AdSter MediationNativeAdView object
  MediationNativeAdView adView = new MediationNativeAdView(this);

  // Add this layout as a parent to your native ad layout
  View nativeAdView = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView, true);

  // Set native elements
  TextView title = adView.findViewById(R.id.titleTextView);
  TextView body = adView.findViewById(R.id.bodyTextView);
  Button cta = adView.findViewById(R.id.ctaButton);
  ImageView logo = adView.findViewById(R.id.iconLogoImageView);
  ImageView choice = adView.findViewById(R.id.choiceImageview);
  TextView info = adView.findViewById(R.id.infoTextView);
  RatingBar ratingBar = adView.findViewById(R.id.ratingBar);
  // MediaView
  FrameLayout mediaView = nativeAdView.findViewById(R.id.mediaView);

  // If MediaView is present add AdSter's MediaView as a child to given MediaView
  if (ad.getMediaView() != null) {
      mediaView.addView(ad.getMediaView());
  }
  adView.setBodyView(body);
  adView.setHeadlineView(title);
  adView.setCtaView(cta);
  adView.setLogoView(logo);
  adView.setAdvertiserView(info);
  adView.setRatingBarView(ratingBar);

  logo.setVisibility(View.VISIBLE);
  // Load logo url using any Image loading library (Glide is just an example here)
  Glide.with(getApplicationContext()).load(ad.getLogo()).into(logo);

  // Set native ad elements with data
  title.setText(ad.getHeadLine());
  body.setText(ad.getBody());
  if(ad.getStarRating()!=null){
    ratingBar.setRating(ad.getStarRating().floatValue());
  }
  cta.setText(ad.getCallToAction());
  info.setText(ad.getAdvertiser());

  Map<String, View> map = new HashMap<>();
  map.put("headline", title);
  map.put("body", body);
  map.put("cta", cta);
  map.put("advertiser",info);
  // Send views to AdSter sdk for tracking click/impressionn etc.
  ad.trackViews(adView, null, map);
  // Set MediationNativeAd object
  adView.setNativeAd(ad);
  // Ad native ad view to container
  container.removeAllViews();
  container.addView(adView);
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
private fun displayNativeAd(ad: MediationNativeAd) {
  // Create AdSter MediationNativeAdView object
  val adView = MediationNativeAdView(this)
  // Add this layout as a parent to your native ad layout
  val nativeAdView: View = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView, true)
  // Set native elements
  val title: TextView = adView.findViewById(R.id.titleTextView)
  val body: TextView = adView.findViewById(R.id.bodyTextView)
  val cta: Button = adView.findViewById(R.id.ctaButton)
  val logo: ImageView = adView.findViewById(R.id.iconLogoImageView)
  val choice: ImageView = adView.findViewById(R.id.choiceImageview)
  val info: TextView = adView.findViewById(R.id.infoTextView)
  val ratingBar : RaringBar = adView.findViewById(R.id.ratingBar)
  // MediaView
  val mediaView: FrameLayout = nativeAdView.findViewById(R.id.mediaView)

  // If MediaView is present add AdSter's MediaView as a child to given MediaView
  if (ad.mediaView != null) {
      mediaView.addView(ad.mediaView)
  }

  adView.bodyView = body
  adView.headlineView = title
  adView.ctaView = cta
  adView.logoView = logo
  adView.advertiserView = info
  adView.ratingBarView = ratingBar
  logo.visibility = View.VISIBLE
  // Load logo url using any Image loading library (Glide is just an example here)
  Glide.with(applicationContext).load(ad.logo).into(logo)

  // Set native ad elements with data
  title.text = ad.headLine
  body.text = ad.body
  cta.text = ad.callToAction
  info.text = ad.advertiser
  starRating?.let { ratingBar.rating = it.toFloat() }

  val map = HashMap<String, View>()
  map["headline"] = title
  map["body"] = body
  map["cta"] = cta
  map["advertiser"] = info

  // Send views to AdSter sdk for tracking click/impressionn etc.
  ad.trackViews(adView, null, map)
  // Set MediationNativeAd object
  adView.nativeAd = ad
  // Ad native ad view to container
  container.removeAllViews()
  container.addView(adView)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Make sure to call `trackViews` and `setNativeAd` method before adding `MediationNativeAdView` to the container.
{% endhint %}

{% hint style="info" %}

```
If you set attachToRoot as false for further customization of nativeAdView before displaying, make sure you attach it to parent afterwards.
In the example provided above it is already set to true.
```

{% endhint %}

{% tabs %}
{% tab title="Java" %}

```javascript
View nativeAdView = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView, false);
parent.addView(nativeAdView); 
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val nativeAdView: View = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView, true)
parent.addView(nativeAdView) 
```

{% endtab %}
{% endtabs %}

6. Call `MediationNativeAd.destroy` when activity or fragment is getting destroyed.

***

### Native Ad in Dynamic Layout

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Builder builder = new AdSterAdLoader.Builder()
        .withAdsListener(new MediationAdListener() {
            @Override
            public void onNativeAdLoaded(MediationNativeAd ad) {
                super.onNativeAdLoaded(ad);

                // Instantiating the dynamicMediaView Object
                FrameLayout dynamicMediaView = new FrameLayout(YourActivity.this);

                // Set the Width and Height based on your requirement
                dynamicMediaView.setLayoutParams(new LinearLayout.LayoutParams(800, 600));

                if (ad.getMediaView() != null) {
                    dynamicMediaView.addView(ad.getMediaView());
                    linearLayout.addView(dynamicMediaView);
                }
            }

            @Override
            public void onFailure(AdError adError) {
                // Handle failure callback here
            }
        })
        .withAdsEventsListener(new AdEventsListener() {
            @Override
            public void onAdClicked() {
                // Handle ad click here
            }

            @Override
            public void onAdImpression() {
                // Handle ad impression here
            }
        });

AdSterAdLoader adLoader = builder.build();
adLoader.loadAd(nativeConfiguration3.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onNativeAdLoaded(ad: MediationNativeAd) {
        super.onNativeAdLoaded(ad)
        //Instantiating the dynamicMediaView Object
        val dynamicMediaView = FrameLayout(this@YourActivity)
        //Set the Width and Height based on your requirement
        dynamicMediaView.layoutParams = LinearLayout.LayoutParams(800,600)
        if (ad.mediaView != null) {
            dynamicMediaView.addView(ad.mediaView)
            linearLayout.addView(dynamicMediaView)
        }
    }

    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }

    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(nativeConfiguration3.build())
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
{% code fullWidth="false" %}

```
Make sure you set LayoutParams of your dynamicMediaView in accordance to parent layout herein Linear Layout.
```

{% endcode %}
{% endhint %}

{% tabs %}
{% tab title="Java" %}

```javascript
dynamicMediaView.setLayoutParams(new LinearLayout.LayoutParams(800, 600));
```

{% endtab %}

{% tab title="Kotlin" %}

```python
dynamicMediaView.layoutParams = LinearLayout.LayoutParams(800,600)
```

{% endtab %}
{% endtabs %}


# Custom Native Ad

Below are the steps to load and show a custom native ad on your app

1. Create your `AdRequestConfiguration` as per the below format

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

2. Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onNativeCustomFormatAdLoaded(@NonNull MediationNativeCustomFormatAd ad) {
        super.onNativeCustomFormatAdLoaded(ad);
        if(ad.getCustomFormatId() == "123456"){
            // Show native custom format for template Id 123456
        } else if (ad.getCustomFormatId() == "654321") {
            // Show native custom format for template Id 654321
        }
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onNativeCustomFormatAdLoaded(ad: MediationNativeCustomFormatAd) {
        super.onNativeCustomFormatAdLoaded(ad)
        //Show native custom format ad here
    }

    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }

    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onNativeCustomFormatAdLoaded` callback method use `MediationNativeCustomFormatAd` object to display custom native ad on your defined layout.
4. Define your native ad layout, below is just an example of a layout

{% code overflow="wrap" %}

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp">
    
    <!-- Icon Logo -->
    <ImageView
      android:id="@+id/iconLogoImageView"
      android:layout_width="54dp"
      android:layout_height="54dp"
      android:visibility="gone"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintBottom_toBottomOf="parent"
      />
    
    <!-- choice Logo -->
    <ImageView
      android:id="@+id/choiceImageview"
      android:layout_width="20dp"
      android:layout_height="20dp"
      android:visibility="visible"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />
    
    <FrameLayout
        android:id="@+id/mediaView"
        android:layout_width="54dp"
        android:layout_height="54dp"
        android:visibility="gone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />
    
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />
    
    <!-- Title -->
    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Sample Title"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />
    
    <!-- Body -->
    <TextView
        android:id="@+id/bodyTextView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Sample Body Text"
        android:textSize="14sp"
        android:layout_marginStart="8dp"
        app:layout_constraintStart_toEndOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/titleTextView" />
    <TextView
        android:id="@+id/infoTextView"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:text="Sample advertiser name"
        android:textSize="15sp"
        app:layout_constraintStart_toEndOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/bodyTextView" />
    
    <!-- CTA Button -->
    <Button
        android:id="@+id/ctaButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Learn More"
        app:layout_constraintStart_toEndOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/infoTextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

{% endcode %}

5. The above sample layout can be used with the `MediationNativeCustomFormatAd` object to render an ad as shown in the below example

{% tabs %}
{% tab title="Java" %}

```java
private void displayNativeCustomFormatAd(MediationNativeCustomFormatAd ad){
  MediationNativeAdView adView =new MediationNativeAdView(this);
  View nativeAdView = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView);
  TextView title = adView.findViewById(R.id.titleTextView);
  TextView body = adView.findViewById(R.id.bodyTextView);
  Button cta = adView.findViewById(R.id.ctaButton);
  ImageView logo = adView.findViewById(R.id.iconLogoImageView);
  TextView info = adView.findViewById(R.id.infoTextView);

  adView.setBodyView(body);
  adView.setHeadlineView(title);
  adView.setCtaView(cta);
  adView.setLogoView(logo);
  adView.setAdvertiserView(info);

  logo.setVisibility(View.VISIBLE);
  Glide.with(getApplicationContext()).load(ad.getImage("Image").getDrawable()).into(logo);

  title.setText(ad.getText("Headline"));
  body.setText(ad.getText("Body"));
  cta.setText(ad.getText("Calltoaction"));
  info.setText(ad.getText("Attribution"));

  cta.setOnClickListener(new View.OnClickListener() {
    @Override
      public void onClick(View v) {
        ad.performClick((String) Objects.requireNonNull(ad.getText("clickactionURL")));
      }
  });

  Map<String, View> map = new HashMap<>();
  map.put("headline", title);
  map.put("body", body);
  map.put("cta", cta);
  map.put("advertiser",info);
  bannerScroll.addView(nativeAdView);
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
private fun displayNativeCustomFormatAd(ad: MediationNativeCustomFormatAd) {
  val adView = MediationNativeAdView(this)
  val nativeAdView = LayoutInflater.from(this).inflate(R.layout.ad_native_layout, adView)
  val title: TextView = adView.findViewById(R.id.titleTextView)
  val body: TextView = adView.findViewById(R.id.bodyTextView)
  val cta: Button = adView.findViewById(R.id.ctaButton)
  val logo: ImageView = adView.findViewById(R.id.iconLogoImageView)
  val info: TextView = adView.findViewById(R.id.infoTextView)

  adView.bodyView = body
  adView.headlineView = title
  adView.ctaView = cta
  adView.logoView = logo
  adView.advertiserView = info

  logo.visibility = View.VISIBLE
  Glide.with(applicationContext).load(ad.getImage("Image").getDrawable()).into(logo)

  title.text = ad.getText("Headline")
  body.text = ad.getText("Body")
  cta.text = ad.getText("Calltoaction")
  info.text = ad.getText("Attribution")

  cta.setOnClickListener {
    ad.performClick(ad.getText("clickactionURL").toString())
  }

  val map: MutableMap<String, View> = HashMap()
  map["headline"] = title
  map["body"] = body
  map["cta"] = cta
  map["advertiser"] = info
  bannerScroll.addView(nativeAdView)
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Make sure to call `trackViews` and `setAdvertiserView` method before adding `MediationNativeCustomFormatAd` to the container.
{% endhint %}

6. Call `MediationNativeCustomFormatAd.destroy` when activity or fragment is getting destroyed.


# App open (Beta)

AdSter SDK also gives the option to load and show AppOpen ad format which is the proprietary Ad format of Google Ad Manager and AdMob. Implementation is similar to that given in this document <https://developers.google.com/admob/android/app-open>. Instead of creating a new `AppOpenAdManager` mentioned in the document use the method below provided by AdSter SDK and follow the implementation on the Activity and Application class just like the document. AdSter SDK provides methods to show and load app-open ads

Create your `AdRequestConfiguration` as per the below format

<pre class="language-java" data-overflow="wrap"><code class="lang-java"><strong>val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
</strong></code></pre>

## Load App Open Ad

Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}
{% code overflow="wrap" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onFailure(@NonNull AdError adError) {
        //Handle failure callback here
    }

    @Override
    public void onAppOpenAdLoaded(@NonNull MediationAppOpenAd ad) {
        super.onAppOpenAdLoaded(ad);
        //Show App Open Ad here
    }
}).withAppOpenAdEventsListener(new AppOpenAdEventsListener() {
    @Override
    public void onAdClicked() {
        // Callback when ad is clicked
    }

    @Override
    public void onAdImpression() {
        // Callback when ad is shown
    }

    @Override
    public void onAdOpened() {
        // Callback when ad is opened
    }

    @Override
    public void onAdClosed() {
        // Callback when ad is cloed
    }

    @Override
    public void onFailure(@Nullable AdError adError) {
        // Calback when there is failure
    }
}).build().loadAd(configuration.build());
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}
{% code overflow="wrap" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener(){
    override fun onAppOpenAdLoaded(ad: MediationAppOpenAd) {
        super.onAppOpenAdLoaded(ad)
        // Show App Open Ad here
    }
    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }

}).withAppOpenAdEventsListener(object : AppOpenAdEventsListener(){
    override fun onAdClicked() {
        // Handle Ad clicked here
    }

    override fun onAdClosed() {
        // Handle Ad closed here
    }

    override fun onAdImpression() {
        // Handle Ad impression here
    }

    override fun onAdOpened() {
        // Handle Ad Open here
    }

    override fun onFailure(adError: AdError?) {
        // Handle Ad Failure here
    }
}).build().loadAd(configuration.build())
```

{% endcode %}
{% endtab %}
{% endtabs %}

***

## Show AppOpen Ad

Inside the `onAppOpenAdLoaded` callback method invoke `showAd(activity)` method of `MediationAppOpenAd` object to show AdSter App Open ad above any activity as shown below

{% tabs %}
{% tab title="Java" %}
{% code overflow="wrap" %}

```java
@Override
public void onAppOpenAdLoaded(@NonNull MediationAppOpenAd ad) {
    super.onAppOpenAdLoaded(ad);
    ad.showAd(activity);
}
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}

<pre class="language-kotlin" data-overflow="wrap"><code class="lang-kotlin">override fun onAppOpenAdLoaded(ad: MediationAppOpenAd) {
<strong>    super.onAppOpenAdLoaded(ad)
</strong>    ad.showAd(activity)
}
</code></pre>

{% endtab %}
{% endtabs %}


# Adaptive Banner Ad (Only for GAM)

Below are the steps to pass predefined custom targeting value in ad request for GAM (Supported by all ad formats)

1. Create your `AdRequestConfiguration` as per the below format

{% code overflow="wrap" %}

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

{% endcode %}

2. Adding preferred adaptive ad type to AdRequest

<details>

<summary>Inline adaptive banner ad</summary>

```java
configuration.addInlineAdaptiveBannerAdSize(width, maxHeight);
```

</details>

<details>

<summary>Current orientation inline adaptive banner ad</summary>

```java
configuration.addCurrentOrientationInlineAdaptiveBannerAdSize(width);
```

</details>

<details>

<summary>Anchored adaptive banner ad</summary>

```java
configuration.addAnchoredAdaptiveBannerAdSize(getAdSize());
```

</details>

{% hint style="info" %}

#### Use the below code to get ad size for anchored adaptive banner ad request :

```java
private Integer getAdSize() {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int adWidthPixels = displayMetrics.widthPixels;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics windowMetrics = this.getWindowManager().getCurrentWindowMetrics();
        adWidthPixels = windowMetrics.getBounds().width();
    }

    float density = displayMetrics.density;
    return (int) (adWidthPixels / density);
}
```

{% endhint %}

3. Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onBannerAdLoaded(@NonNull MediationBannerAd ad) {
        super.onBannerAdLoaded(ad);
        // Show banner ad here
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        // Handle failure here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onBannerAdLoaded(ad: MediationBannerAd) {
        super.onBannerAdLoaded(ad)
        // Show banner ad here
    }

    override fun onFailure(adError: AdError) {
        // Handle failure here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }
    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onBannerAdLoaded` callback method invoke `getView()` method of `MediationnBannerAd` object to add an AdSter banner view to the given layout as shown below

```java
container.removeAllViews();
container.addView(ad.getView());
```

4. Call `MediationBannerAd.destroy()` When activity/fragment is destroyed or detached.


# Render Unified Ad (Only for GAM)

Below are the steps to load and render a unified ad on your app

1. Create your `AdRequestConfiguration` as per the below format

{% code overflow="wrap" %}

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

{% endcode %}

2. Call `loadAd()` method as per the below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onBannerAdLoaded(@NonNull MediationBannerAd ad) {
        super.onBannerAdLoaded(ad);
        //Show banner ad here
    }

    @Override
    public void onNativeAdLoaded(@NonNull MediationNativeAd ad) {
        super.onNativeAdLoaded(ad);
        //Show native ad here
    }

    @Override
    public void onNativeCustomFormatAdLoaded(@NonNull MediationNativeCustomFormatAd ad) {
        super.onNativeCustomFormatAdLoaded(ad);
        //Show native custom format ad here
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onBannerAdLoaded(ad: MediationBannerAd) {
        super.onBannerAdLoaded(ad)
        //Show banner ad here
    }

    override fun onNativeAdLoaded(ad: MediationNativeAd) {
        super.onNativeAdLoaded(ad)
        //Show native ad here
    }

    override fun onNativeCustomFormatAdLoaded(ad: MediationNativeCustomFormatAd) {
        super.onNativeCustomFormatAdLoaded(ad)
        //Show native custom format ad here
    }

    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }

    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
`onNativeAdLoaded()` - [Click here](/how-to-render-an-ad/native-ad#kotlin) for Rendering implementation\
`onBannerAdLoaded()` - [Click here](/how-to-render-an-ad/banner-ad) for Rendering implementation\
`onNativeCustomFormatAdLoaded()` - [Click here](/how-to-render-an-ad/native-ad-1) for Rendering implementation
{% endhint %}


# How to pass predefined custom targeting values in ad request (Only for GAM)

Below are the steps to pass predefined custom targeting value in ad request for GAM (Supported by all ad formats)

1. Create your `AdRequestConfiguration` as per the below format

{% code overflow="wrap" %}

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

{% endcode %}

2. Adding predefined ad targeting parameters to AdRequest

<details>

<summary>Single key with single value</summary>

```java
configuration.addCustomTargetingValue("YOUR_KEY","YOUR_VALUE")
```

</details>

<details>

<summary>Single key with multiple values</summary>

```java
configuration.addCustomTargetingValue("YOUR_KEY",List<String>)
```

</details>

<details>

<summary>Multiple keys with single value</summary>

```java
configuration.addCustomTargetingValue("YOUR_KEY","YOUR_VALUE")
             .addCustomTargetingValue("YOUR_KEY","YOUR_VALUE")
```

</details>

<details>

<summary>Multiple keys with multiple values</summary>

```java
configuration.addCustomTargetingValue("YOUR_KEY",List<String>)
             .addCustomTargetingValue("YOUR_KEY",List<String>)
```

</details>

{% hint style="info" %}

#### Custom ad request can be created for all the ad types.

Here is an example of implementation with banner ad.
{% endhint %}

3. Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onBannerAdLoaded(@NonNull MediationBannerAd ad) {
        super.onBannerAdLoaded(ad);
        // Show banner ad here
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        // Handle failure here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onBannerAdLoaded(ad: MediationBannerAd) {
        super.onBannerAdLoaded(ad)
        // Show banner ad here
    }

    override fun onFailure(adError: AdError) {
        // Handle failure here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }
    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onBannerAdLoaded` callback method invoke `getView()` method of `MediationnBannerAd` object to add an AdSter banner view to the given layout as shown below

```java
container.removeAllViews();
container.addView(ad.getView());
```

4. Call `MediationBannerAd.destroy()` When activity/fragment is destroyed or detached.


# How to pass publisher provided identifiers in ad request (PPID) (Only for GAM)

Below are the steps to pass PPID with ad request for GAM (Supported by all ad formats)

1. Create your `AdRequestConfiguration` as per the below format

{% code overflow="wrap" %}

```java
val configuration = AdRequestConfiguration.Companion.builder(context, "Your_placement_name");
```

{% endcode %}

2. Adding PPID to AdRequest

{% code overflow="wrap" %}

```java
configuration.publisherProvidedId("YOUR_PPID");
```

{% endcode %}

{% hint style="info" %}

#### PPID can be passed for all ad type ad requests.

Here is an example of implementation with banner ad.
{% endhint %}

3. Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onBannerAdLoaded(@NonNull MediationBannerAd ad) {
        super.onBannerAdLoaded(ad);
        // Show banner ad here
    }

    @Override
    public void onFailure(@NonNull AdError adError) {
        // Handle failure here
    }
}).withAdsEventsListener(new AdEventsListener() {
    @Override
    public void onAdClicked() {
        //Handle ad click here
    }

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onBannerAdLoaded(ad: MediationBannerAd) {
        super.onBannerAdLoaded(ad)
        // Show banner ad here
    }

    override fun onFailure(adError: AdError) {
        // Handle failure here
    }
}).withAdsEventsListener(object : AdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }
    override fun onAdImpression() {
        //Handle ad impression here
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onBannerAdLoaded` callback method invoke `getView()` method of `MediationnBannerAd` object to add an AdSter banner view to the given layout as shown below

```java
container.removeAllViews();
container.addView(ad.getView());
```

4. Call `MediationBannerAd.destroy()` When activity/fragment is destroyed or detached.


# TEST AD UNITS

### Sample test adunits by Adster to ensure Ads are coming and is displayed inAPP by the developers.

### Adster provides several test ad units for development and testing purposes:

* **Adster\_Unified\_Test**: Can respond with either banner or native ads
* **Adster\_Native\_Test**: Will respond with native ads only
* **Adster\_Banner\_Test**: Will respond with banner ads only
* **Adster\_Appopen\_Test**: Will respond with App Open ads only
* **Adster\_Interstitial\_Test**: Will respond with Interstitial ads only
* **Adster\_FS\_Native\_Test**: Will respond with native ads only for full screen opportunity, in case of swipe actions
* **Adster\_FS\_Unified\_Test**: Will respond with native or banner like 320x480 ads only for full screen opportunity, in case of swipe actions
* **adster\_banner\_320x50**: Test placement for standard 320x50 banner ads
* **adster\_banner\_300x250**: Test placement for medium rectangle 300x250 banner ads
* **adster\_interstitial\_test**: Test placement for interstitial ads
* **adster\_rewarded\_test**: Test placement for rewarded ads

E.g.

{% code fullWidth="true" %}

```
val configuration = AdRequestConfiguration.Companion.builder(context, "Adster_Banner_Test");
```

{% endcode %}


# Manifest Changes Required for SDK

Please add these changes to the manifest of your application

{% code overflow="wrap" %}

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

{% endcode %}

***

{% hint style="warning" %}
If you don\`t have an admob account and want to test the initialization of the SDK, please also add these to the manifest so that the SDK initialization can be completed.
{% endhint %}

{% code overflow="wrap" %}

```xml
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"                 android:value="ca-app-pub-7640426597645136~3443205346" />
```

{% endcode %}


# Integrate Ads & APP Ads For Easy Management

We have built a easy to use UI for adding / updating ads.txt from UI for product & Adops teams. Its a one time integration where domain/ads.txt and domain/app-ads.txt needs to be linked to our URL. Everytime when a new entry is added we publish the same in our URL and hence website needs to pick from this published url of adster once a day or once in 2-3 days.&#x20;

Product / Ops: From app.adster.tech, navigate to "Managed Ads TXT" section, add your domain name like "<https://adster.tech>" and we will fetch the existing file. And then you can make the entries, and save the same to generate a URL. \
\
E.g. URL: <https://storage.googleapis.com/public-assets-adstxtmanage/Citymall> main website-app-ads.txt from where ads.txt needs to be read and updated in the domain


