# SDK Implementation Guide

This guide provides a comprehensive step-by-step process for integrating the AdSter SDK into your Android application. Ensure you follow each section carefully for successful implementation

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

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

## **Manifest Changes Required for SDK**

Please add these changes to the manifest of your application

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

{% 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 %}

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

## Configuration Steps

**Adding Dependency**

* Open the `build.gradle` (Module: app) file.
* Find the dependencies block and add the following SDK dependency.
* Add these proguard rules / lines in the final release build\
  -keep class com.adster.\*\* { \*; }

{% code fullWidth="true" %}

```
implementation 'com.adstertech:orchestrationsdk-lite:2.7.1'
```

{% endcode %}


# Initializing the SDK

To Initialize the SDK call the intitializeSDK() function in the application class of the app. It is recommended to call the function as soon as possible.

The initializeSDK() function returns a list of AdapterStatus , and the function is called as follows:

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

```java
AdSter.INSTANCE.initializeSdk(getApplicationContext(), AdapterStatus -> {
    // Initialization completes here
})
```

{% endtab %}

{% tab title="Kotlin" %}

```java
AdSter.initializeSdk(getApplicationContext(), object : InitializationListener {
    override fun onInitializationComplete(adapterStatus: List<AdapterStatus>) {
        // Initialization completes here
    }
})
```

{% endtab %}
{% endtabs %}

Note : All load ad requests are to be called only after the completion of the initialization of the SDK.


# App Open

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

## Load App Open Ad

Call `loadAd()` method as per below format

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

```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) {
        // Callback when there is failure
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())
```

{% 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 %}


# Banner Ad

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

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

2. 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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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

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

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

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
binding.container.apply {
  removeAllViews()
  addView(ad.view)
}
```

{% endtab %}
{% endtabs %}

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


# Interstitial Ad

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

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

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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

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

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

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

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

    @Override
    public void onAdOpened() {
        //Handle ad open here
    }

    @Override
    public void onAdClosed() {
        //Handle ad closed here
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onInterstitialAdLoaded(ad: MediationInterstitialAd) {
        super.onInterstitialAdLoaded(ad)
        //Show interstitial ad here
    }

    override fun onFailure(adError: AdError) {
        //Handle failure callback here
    }
}).withInterstitialAdEventsListener(object : InterstitialAdEventsListener() {
    override fun onAdClicked() {
        //Handle ad click here
    }
    
    override fun onAdImpression() {
        //Handle ad impression here
    }
    
    override fun onAdOpened() {
        //Handle ad open here
    }
    
    override fun onAdClosed() {
        //Handle ad close here
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onInterstitialAdLoaded` callback method invoke `showAd(activity)` method of `MediationInterstitialAd` object to show AdSter interstitial ad above any activity as shown below

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

<pre class="language-java"><code class="lang-java"><strong>@Override
</strong>public void onInterstitialAdLoaded(@NonNull MediationInterstitialAd ad) {
     super.onInterstitialAdLoaded(ad);
     ad.showAd(getApplicationContext());
  }

</code></pre>

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onInterstitialAdLoaded (ad: MediationInterstitialAd) {
    super.onInterstitialAdLoaded (ad)
    ad.showAd(activity);
}
```

{% endtab %}
{% endtabs %}

4. Make sure to pass only Activity\`s context as parameter to `showAd()`


# Rewarded Ad

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

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

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

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

{% endcode %}
{% endtab %}

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

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

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

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

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

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

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

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

    @Override
    public void onUserEarnedReward(@NonNull Reward reward) {
        //Handle ad click here
    }

    @Override
    public void onVideoComplete() {
        //Handle ad click here
    }

    @Override
    public void onVideoClosed() {
        //Handle ad click here
    }

    @Override
    public void onVideoStart() {
        //Handle ad click here
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onRewardedAdLoaded(ad: MediationRewardedAd) {
        super.onRewardedAdLoaded(ad)
        //Show Rewarded ad here
    }

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

    override fun onAdImpression() {
        //Handle ad click here
    }

    override fun onUserEarnedReward(reward: Reward) {
        //Handle ad click here
    }

    override fun onVideoComplete() {
        //Handle ad click here
    }

    override fun onVideoClosed() {
        //Handle ad click here
    }

    override fun onVideoStart() {
        //Handle ad click here
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())

```

{% endtab %}
{% endtabs %}

3. Inside the `onRewardedAdLoaded` callback method invoke `showAd(activity)` method of `MediationRewardedAd` object to show AdSter rewarded ad above any activity as shown below

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

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

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
override fun onRewardedAdLoaded (ad: MediationRewardedAd) {
    super.onRewardedAdLoaded (ad)
    ad.showAd(activity);
}
```

{% endtab %}
{% endtabs %}

4. Make sure to pass only Activity\`s context as parameter to `showAd()`


# 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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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 %}


# Native Reward Ad

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

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

2. Adding PPID to AdRequest

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

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

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

<pre class="language-java"><code class="lang-java">AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onNativeRewardAdLoaded(@NonNull MediationNativeRewardAd ad) {
        super.onNativeRewardAdLoaded(ad);
<strong>        //Show native reward ad here
</strong>    }

    @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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
</code></pre>

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {    
    override fun onNativeRewardAdLoaded(ad: MediationNativeRewardAd) {
        super.onNativeRewardAdLoaded(ad)
        //Show native reward 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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

4. Inside the `onNativeRewardAdLoaded` callback method use `MediationNativeRewardAd` object to display native reward ad on your defined layout.
5. The layout below is only an example. The client app can design the reward UI independently.

{% 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/nativeRewardLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:padding="16dp">

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

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

            <ImageView
                android:id="@+id/iconLogoImageView"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:scaleType="centerCrop" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="12dp"
                android:layout_weight="1"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/advertiserTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:textColor="@android:color/black"
                    android:textSize="14sp"
                    tools:text="Advertiser" />

                <TextView
                    android:id="@+id/titleTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="2"
                    android:textColor="@android:color/black"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    tools:text="Native Reward Offer" />
            </LinearLayout>
        </LinearLayout>

        <FrameLayout
            android:id="@+id/mediaView"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:layout_marginTop="16dp" />

        <TextView
            android:id="@+id/bodyTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:ellipsize="end"
            android:maxLines="4"
            android:textColor="@android:color/black"
            android:textSize="14sp"
            tools:text="Complete the offer to receive the reward." />

        <Button
            android:id="@+id/ctaButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            tools:text="Redeem now" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
```

{% endcode %}

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

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

```java
private MediationNativeRewardAd nativeRewardAd;

private void displayNativeRewardAd(MediationNativeRewardAd ad) {
    nativeRewardAd = ad;

    // Create AdSter MediationNativeRewardAdView object.
    MediationNativeRewardAd adView = new MediationNativeRewardAd(this);

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

    TextView advertiser = adView.findViewById(R.id.advertiserTextView);
    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);
    FrameLayout mediaContainer = nativeRewardAdView.findViewById(R.id.mediaView);

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

    advertiser.setText(ad.getAdvertiser());
    title.setText(ad.getHeadLine());
    body.setText(ad.getBody());
    cta.setText(ad.getCallToAction());

    if (ad.getLogo() != null) {
        // Load logo url using any image loading library. Glide is used only as an example.
        Glide.with(getApplicationContext()).load(ad.getLogo()).into(logo);
    }

    if (ad.getMediaView() != null) {
        View mediaView = ad.getMediaView();
        ViewParent parent = mediaView.getParent();
        if (parent instanceof ViewGroup) {
            ((ViewGroup) parent).removeView(mediaView);
        }
        mediaContainer.removeAllViews();
        mediaContainer.addView(mediaView);
        adView.setMediaView(mediaView);
    }

    Map<String, View> clickableViews = new HashMap<>();
    clickableViews.put("headline", title);
    clickableViews.put("body", body);
    clickableViews.put("cta", cta);
    clickableViews.put("advertiser", advertiser);

    // Send views to AdSter SDK for click and impression tracking.
    ad.trackViews(adView, logo, clickableViews);

    // Set MediationNativeRewardAd object.
    adView.setNativeRewardAd(ad);

    container.removeAllViews();
    container.addView(adView);

    if (ad.getHasReward()) {
        // Optional reward metadata. Client app owns how this reward is displayed or fulfilled.
        JsonObject reward = ad.getReward();
    }
}

@Override
protected void onDestroy() {
    if (nativeRewardAd != null) {
        nativeRewardAd.destroy();
        nativeRewardAd = null;
    }
    super.onDestroy();
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
private var nativeRewardAd: MediationNativeRewardAd? = null

private fun displayNativeRewardAd(ad: MediationNativeRewardAd) {
    nativeRewardAd = ad

    // Create AdSter MediationNativeRewardAdView object.
    val adView = MediationNativeRewardAdView(this)

    // Add this layout as a parent to your native reward ad layout.
    val nativeRewardAdView: View = LayoutInflater.from(this)
        .inflate(R.layout.native_reward_ad_layout, adView, true)

    val advertiser: TextView = adView.findViewById(R.id.advertiserTextView)
    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 mediaContainer: FrameLayout = nativeRewardAdView.findViewById(R.id.mediaView)

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

    advertiser.text = ad.advertiser
    title.text = ad.headLine
    body.text = ad.body
    cta.text = ad.callToAction

    ad.logo?.let { logoUrl ->
        // Load logo url using any image loading library. Glide is used only as an example.
        Glide.with(applicationContext).load(logoUrl).into(logo)
    }

    ad.mediaView?.let { mediaView ->
        (mediaView.parent as? ViewGroup)?.removeView(mediaView)
        mediaContainer.removeAllViews()
        mediaContainer.addView(mediaView)
        adView.mediaView = mediaView
    }

    val clickableViews = hashMapOf<String, View>(
        "headline" to title,
        "body" to body,
        "cta" to cta,
        "advertiser" to advertiser
    )

    // Send views to AdSter SDK for click and impression tracking.
    ad.trackViews(adView, logo, clickableViews)

    // Set MediationNativeRewardAd object.
    adView.nativeRewardAd = ad

    container.removeAllViews()
    container.addView(adView)

    if (ad.hasReward) {
        // Optional reward metadata. Client app owns how this reward is displayed or fulfilled.
        val reward = ad.reward
    }
}

override fun onDestroy() {
    nativeRewardAd?.destroy()
    nativeRewardAd = null
    super.onDestroy()
}
```

{% endtab %}
{% endtabs %}

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


# 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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
        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 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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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"
      />
    
    <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("Calltoaction");
      }
  });
  
  bannerScroll.addView(nativeAdView);
  ad.trackViewability(adView);
  ad.recordImpression();
}
```

{% 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("Calltoaction")
  }
  
  bannerScroll.addView(nativeAdView)
  ad.trackViewability(adView)
  ad.recordImpression()
}
```

{% 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.


# Carousel Banner Ad

Below are the steps to load and render multiple banner Ads on your app.

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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

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

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onCarouselBannerAdLoaded(@NonNull MediationCarouselBannerAd ad) {
        // To get the ads
        for (MediationBannerAd bannerAd : ad.getAds()) {
            // To get the ad eCPM 
            Double eCPM = ad.getECPM();
            // 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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
    override fun onBannerAdLoaded(ad: MediationBannerAd) {
        // To get the ads
        for(ad in ad.ads){
            // To get the ad eCPM
            val eCPM = ad.eCPM
            // 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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())
```

{% endtab %}
{% endtabs %}

3. Inside the `onCarouselBannerAdLoaded` callback method invoke `getView()` method of `MediationnBannerAd` object to add a Banner View to the given layout as shown below

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

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

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
binding.container.apply {
  removeAllViews()
  addView(ad.view)
}
```

{% endtab %}
{% endtabs %}

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


# Carousel Native Ad

Below are the steps to load and show multiple native ads on your app.

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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

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

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onCarouselNativeAdLoaded(@NonNull MediationCarouselNativeAd ad) {
        // To get the ads
        for (MediationNativeAd nativeAd : ad.getAds()) {
            displayNativeAd(nativeAd);
            //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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {    
    override fun onCarouselNativeAdLoaded(ad: MediationCarouselNativeAd) {
        // To get the ads
        for(nativeAd in ad.ads){
            displayNativeAd(nativeAd)
        }
    }

    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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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.


# In-stream Video (Beta)

AdSter SDK also gives the option to load and show in-stream video ad format which is the proprietary Ad format of IMA SDK.&#x20;

Create your `AdRequestConfiguration` as per the below format

{% code overflow="wrap" %}

```java
AdRequestConfiguration configuration = AdRequestConfiguration.Companion
    .builder(context, "Your_placement_name")
    .addVideoPlayer(playerView, audioManager)
    .setContentUrl("https://your-video-url.mp4")
    .build();

```

{% endcode %}

## Load and show In-stream Video Ad

Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}
{% code fullWidth="true" %}

```java
AdSterAdLoader.Companion.builder()
    .withAdsListener(new MediationAdListener() {
        @Override
        public void onVideoAdLoaded(@NonNull MediationVideoAd ad) {
            Log.d("AdCallback", "Ad Loaded");
        }

        @Override
        public void onFailure(@NonNull AdError error) {
            Log.e("AdCallback", "Ad Load Failed: " + error.getErrorMessage());
        }
    })
    .withVideoAdEventsListener(new VideoAdEventsListener() {
        @Override public void onAdPlayed() {}
        @Override public void onAdSkipped() {}
        @Override public void onAdStopped() {}
        @Override public void onAllAdCompleted() {}
        @Override public void onContentPauseRequested() {}
        @Override public void onContentResumeRequested() {}
        @Override public void onAdLoadFailure(@NonNull AdError error) {}
        @Override public void onAdClicked() {}
        @Override public void onVolumeChanged(int delta) {}
        @Override public void onAdTapped() {}
        @Override public void onAdPaused() {}
        @Override public void onSkippableStateChanged() {}
    })
    .build()
    .loadAd(configuration);
```

{% endcode %}
{% endtab %}

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

```kotlin
AdSterAdLoader.builder()
    .withAdsListener(object : MediationAdListener {
        override fun onVideoAdLoaded(ad: MediationVideoAd) {
            Log.d("AdCallback", "Ad Loaded")
        }

        override fun onFailure(error: AdError) {
            Log.e("AdCallback", "Ad Load Failed: ${error.errorMessage}")
        }
    })
    .withVideoAdEventsListener(object : VideoAdEventsListener() {
        override fun onAdPlayed() {}
        override fun onAdSkipped() {}
        override fun onAdStopped() {}
        override fun onAllAdCompleted() {}
        override fun onContentPauseRequested() {}
        override fun onContentResumeRequested() {}
        override fun onAdLoadFailure(error: AdError) {}
        override fun onAdClicked() {}
        override fun onVolumeChanged(volumeDelta: Int) {}
        override fun onAdTapped() {}
        override fun onAdPaused() {}
        override fun onSkippableStateChanged() {}
    })
    .build()
    .loadAd(configuration)
```

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

{% hint style="success" %}
Reference for sample implementation\
<https://storage.googleapis.com/adster-unity-bridge-docs/in-stream-ads/AdActivityVideo.java>\
<https://storage.googleapis.com/adster-unity-bridge-docs/in-stream-ads/activity_ad_video.xml>
{% endhint %}


# Banner Video (Beta)

AdSter SDK also gives the option to load and show in-stream video ad in a banner format.&#x20;

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 and show Banner Video Ad

Call `loadAd()` method as per below format

{% tabs %}
{% tab title="Java" %}
{% code fullWidth="true" %}

```java
AdSterAdLoader.Companion.builder().withAdsListener(new MediationAdListener() {
    @Override
    public void onBannerVideoAdLoaded (@NonNull MediationBannerVideoAd ad){ 
        //Use the ad object provided here to display the ad
    }

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

    @Override
    public void onAdImpression() {
        //Handle ad impression here
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId,@NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build());
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}

<pre class="language-kotlin" data-overflow="wrap" data-full-width="false"><code class="lang-kotlin"><strong>AdSterAdLoader.builder().withAdsListener(object : MediationAdListener() {
</strong>    override fun onBannerVideoAdLoaded(ad: MediationBannerVideoAd) {
        //Use the ad object provided here to display the ad
    }

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

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

    override fun onAdRevenuePaid(
        revenue: Double,
        adUnitId: String,
        network: String,
        currency: String,
        precisionType: PrecisionType
    ) {
        // Callback which provides revenue and the network which provided it
    }
}).build().loadAd(configuration.build())
</code></pre>

{% endtab %}
{% endtabs %}

Also use the `pause()`,`resume()` and `destroy()` functions of the ad object provided in `onBannerVideoAdLoaded(MediationBannerVideoAd ad)` to pause , resume and destroy the video when the fragment or the activity is being paused , resumed and destroyed respectively.\
\
Below is an example :

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

```java
private MediationBannerVideoAd bannerVideoAd = null;

@Override
protected void onPause() {
    super.onPause();
    if (bannerVideoAd != null) {
        bannerVideoAd.pause();
    }
}

@Override
protected void onResume() {
    super.onResume();
    if (bannerVideoAd != null) {
        bannerVideoAd.resume();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (bannerVideoAd != null) {
        bannerVideoAd.destroy();
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
private var bannerVideoAd : MediationBannerVideoAd? = null

override fun onPause() {
    super.onPause()
    bannerVideoAd?.pause()
}
    
override fun onResume() {
    super.onResume()
    bannerVideoAd?.resume()
}
    
override fun onDestroy() {
    super.onDestroy()
    bannerVideoAd?.destroy()
}
```

{% 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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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 :
{% endhint %}

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

```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);
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
fun getAdSize(): Int {
    val displayMetrics = getResources().displayMetrics
    var adWidthPixels = displayMetrics.widthPixels

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val windowMetrics = this.windowManager.currentWindowMetrics
        adWidthPixels = windowMetrics.bounds.width()
    }

    val density = displayMetrics.density
    return (adWidthPixels / density).toInt()
}
```

{% endtab %}
{% endtabs %}

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId, @NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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.


# Collapsible Anchored Adaptive Banner Ad (Only for GAM)

Below are the steps to request a collapsible anchored adaptive banner ad.

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

2. Adding anchored adaptive ad type to AdRequest.

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

```java
configuration.addAnchoredAdaptiveBannerAdSize(300, CollapsiblePlacement.BOTTOM);
```

{% endcode %}
{% endtab %}

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

```kotlin
configuration.addAnchoredAdaptiveBannerAdSize(320, CollapsiblePlacement.TOP)
```

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

{% hint style="info" %}
The collapsible placement defines how the expanded region anchors to the banner ad.
{% endhint %}

| Placement value | Behavior                                                                | Intended use case                             |
| --------------- | ----------------------------------------------------------------------- | --------------------------------------------- |
| TOP             | The top of the expanded ad aligns to the top of the collapsed ad.       | The ad is placed at the top of the screen.    |
| BOTTOM          | The bottom of the expanded ad aligns to the bottom of the collapsed ad. | The ad is placed at the bottom of the screen. |

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId, @NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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
        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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId, @NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
        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 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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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-2) for Rendering implementation
{% endhint %}


# How to pass predefined custom targeting values in ad request

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

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId, @NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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)

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

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

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

{% endcode %}
{% endtab %}

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

```kotlin
val configuration = AdRequestConfiguration.builder(context, "Your_placement_name")
```

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

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
    }
    
    @Override
    public void onAdRevenuePaid(double revenue, @NotNull String adUnitId, @NotNull String network, @NotNull String currency, @NotNull PrecisionType precisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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
    }
    
    override fun onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: PrecisionType) {
        // Callback which provides revenue and the network which provided it
    }
}).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 ad units by Adster to ensure Ads are coming and is displayed in app by the developers.&#x20;

Banner (320x50) - <mark style="color:$success;">**`banner_320x50`**</mark>

Banner (300x250) - <mark style="color:$success;">**`banner_300x250`**</mark>

Adaptive Banner - <mark style="color:$success;">**`banner_adaptive`**</mark>

Native - <mark style="color:$success;">**`native`**</mark>&#x20;

Appopen - <mark style="color:$success;">**`appopen`**</mark>&#x20;

Interstitial - <mark style="color:$success;">**`interstitial`**</mark>&#x20;

Unified - <mark style="color:$success;">**`unified`**</mark>&#x20;

Rewarded - <mark style="color:$success;">**`rewarded`**</mark>

Placement code snippet  :point\_down:\
val configuration = AdRequestConfiguration.Companion.builder(context, "<mark style="color:$success;">**`banner_300x250`**</mark>");


# 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


