> For the complete documentation index, see [llms.txt](https://aatkit.gitbook.io/android-integration/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aatkit.gitbook.io/android-integration/formats/native-ad/basic-integration.md).

# Basic Integration

Native ads are presented to the user via native Android UI components. This enables you to layout ad assets to match the look and feel of your app. When a placement loads a native ad, you can retrieve the native ad assets wrapped in an instance of type [NativeAdData](https://android-sdk.aatkit.com/references/-a-a-t-kit/com.intentsoftware.addapptr.ad/-native-ad-data/index.html).

### Create Placement

To create an instance of [NativeAdPlacement](https://android-sdk.aatkit.com/references/-a-a-t-kit/com.intentsoftware.addapptr/-native-ad-placement/index.html), use the following API:

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

```java
NativeAdPlacement placement = AATKit.createNativeAdPlacement("<PLACEMENT_NAME>", supportsMainImage);
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val placement = AATKit.createNativeAdPlacement("<PLACEMENT_NAME>", supportsMainImage)
```

{% endtab %}
{% endtabs %}

The argument `supportsMainImage` determines if the placement will use the main image asset. Remember that if the main image is used, it must be displayed.

### Listen to Callbacks

Through the use of [NativePlacementListener](https://android-sdk.aatkit.com/references/-a-a-t-kit/com.intentsoftware.addapptr/-native-placement-listener/index.html), you can listen to the different placement callbacks.

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

```java
placement.setListener(this);
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
placement.listener = this
```

{% endtab %}
{% endtabs %}

### Request Ad

To request a native ad, use the following API:

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

```java
placement.reload();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
placement.reload()
```

{% endtab %}
{% endtabs %}

### Retrieve the Native Ad

After receiving a native ad through the `onHaveAd` callback, you can retrieve the native ad data of type [NativeAdData](https://android-sdk.aatkit.com/references/-a-a-t-kit/com.intentsoftware.addapptr.ad/-native-ad-data/index.html) using the following API:

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

```java
NativeAdData nativeAd = placement.getNativeAd();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val nativeAd = placement.getNativeAd()
```

{% endtab %}
{% endtabs %}

### Report adspace

For native placements, it is necessary to report ad spaces manually. Every time you want to display an native ad, call:

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

```java
placement.countAdSpace();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
placement.countAdSpace()
```

{% endtab %}
{% endtabs %}

### Ad Info <a href="#a-d-info" id="a-d-info"></a>

After loading a native ad, you can access the loaded ad information by accessing the `adInfo` property of the loaded `nativeAd`:

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

```java
AdInfo adInfo = nativeAd.getAdInfo();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val info = nativeAd.adInfo
```

{% endtab %}
{% endtabs %}

### Retrieve the Native Assets

These so-called native assets can assemble your native ad, according to your app's look and feel. The following image shows an example native ad and the corresponding AATKit methods for retrieving each asset.

<figure><img src="/files/3MjRxOpwsQfctRpl0Jrf" alt=""><figcaption><p>Native Ad Assets</p></figcaption></figure>

<figure><img src="/files/GuK5GYDnmgszbVX4errv" alt=""><figcaption><p>Native Ad layout</p></figcaption></figure>

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

```java
// Ad Title
titleView.setText(nativeAd.getTitle());
// Ad Icon
String iconImageUrl = nativeAd.getIconUrl(); // You should download the icon image using this URL
// Ad Main Image
String mainImageURL = nativeAd.getImageUrl(); // You should download the main image using this URL
// Ad Body
descriptionView.setText(nativeAd.getDescription());
// Ad Identifier
advertiserView.setText(nativeAd.getAdvertiser());
// Ad CTA Title
ctaView.setText(nativeAd.getCallToAction());
// Ad Rating
NativeAd.NativeAdRating rating = nativeAd.getRating();
if (rating != null) {
    String ratingText = rating.getValue() + "/" + rating.getScale();
    ratingView.setText(ratingText);
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Ad Title
titleView.text = nativeAd.title
// Ad Icon
val iconImageUrl = nativeAd.iconUrl // You should download the icon image using this URL
// Ad Main Image
val mainImageURL = nativeAd.imageUrl // You should download the main image using this URL
// Ad Body
descriptionView.text = nativeAd.description
// Ad Identifier
advertiserView.text = nativeAd.advertiser
// Ad CTA Title
ctaView.text = nativeAd.callToAction
// Ad Rating
val rating = nativeAd.rating
if (rating != null) {
    val ratingText = "${rating.value}/${rating.scale}"
    ratingView.text = ratingText
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
If the ad network provides a rating for the retrieved native ad, [NativeAdData](https://android-sdk.aatkit.com/references/-a-a-t-kit/com.intentsoftware.addapptr.ad/-native-ad-data/index.html) will provide it as an NativeAdRating instance.
{% endhint %}

### Track Native Ad

A tracking view is a ViewGroup instance that is used by the ad network to track impressions and clicks. This means the instance is checked on runtime whether it's visible on the screen and an impression is counted accordingly. A click is also registered on the instance provided. Keep in mind that the ad networks track impressions based on a few conditions being met. A tracking view has to be visible for at least a few seconds on the screen (usually 1-2 seconds), plus a more significant portion of the ViewGroup instance has to be visible (usually \~50% of the view has to be visible). Tracking an impression and registering clicks is thus completely dependent on a tracking view being assigned to the native ad that has been provided by the AATKit.

To set the tracking view, use the `NativeAdData` method:&#x20;

```swift
fun attachToLayout(layout: ViewGroup, mainImageView: View?, iconView: View?, ctaView: View?)
```

* `layout`: The ViewGroup that will be used to track impressions and clicks.
* `mainImageView`: The main image asset view.
* `iconView`: The icon asset view.
* `ctaView`: The call to action view.

Example:

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

```java
nativeAd.attachToLayout(nativeAdContainerView,
                      adMainImageView,
                      adIconImageView,
                      adCTAView);
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
nativeAd.attachToLayout(nativeAdContainerView,
                      adMainImageView,
                      adIconImageView,
                      adCTAView)
```

{% endtab %}
{% endtabs %}

Also, you **must** remove the tracking view from the native ad, when the native ad isn't needed anymore or is replaced.

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

```java
nativeAd.detachFromLayout();
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
nativeAd.detachFromLayout()
```

{% endtab %}
{% endtabs %}

### Complete Code Example

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

```java
private NativeAdPlacement nativeAdPlacement = AATKit.createNativeAdPlacement("<PLACEMENT_NAME>", true);

@Override
protected void onResume() {
    super.onResume();
    // [IMPORTANT] Notify AATKit about activity lifecycle
    AATKit.onActivityResume(this);

    // Set placement listener to listen to the callbacks
    nativeAdPlacement.setListener(this);
    // Request a native ad
    nativeAdPlacement.reload();
}

@Override
protected void onPause() {
    // [IMPORTANT] Notify AATKit about activity lifecycle
    AATKit.onActivityPause(this);
    super.onPause();
}

// NativePlacementListener:
@Override
public void onHaveAd(@NonNull Placement placement) {
    // Tha placement has loaded a new ad
    NativeAdData nativeAd = nativeAdPlacement.getNativeAd();
    if (nativeAd == null) {
        return;
    }
    // Prepare needed views
    ViewGroup nativeAdView = (ViewGroup) getLayoutInflater().inflate(R.layout.your_native_ad_layout, null);
    ImageView mainImageView = nativeAdView.findViewById(R.id.mainImageView);
    TextView titleView = nativeAdView.findViewById(R.id.titleView);
    ImageView iconView = nativeAdView.findViewById(R.id.iconView);
    TextView descriptionView = nativeAdView.findViewById(R.id.adDescriptionView);
    TextView ctaView = nativeAdView.findViewById(R.id.CTA_view);
    TextView advertiserView = nativeAdView.findViewById(R.id.advertiser_textView);

    // Report Ad Space
    nativeAdPlacement.countAdSpace();
    // Ad Title
    titleView.setText(nativeAd.getTitle());
    // Ad Icon
    loadImage(iconView, nativeAd.getIconUrl());
    // Ad Main Image
    loadImage(mainImageView, nativeAd.getImageUrl());
    // Ad Body
    descriptionView.setText(nativeAd.getDescription());
    // Ad Identifier
    advertiserView.setText(nativeAd.getAdvertiser());
    // Ad CTA Title
    ctaView.setText(nativeAd.getCallToAction());

    // Set the tracking view
    nativeAd.attachToLayout(nativeAdView, mainImageView, iconView, ctaView);

    // TODO: Present prepared ad on screen
}

@Override
public void onNoAd(@NonNull Placement placement) {
    // The placement could not load a new ad
}

@Override
public void onPauseForAd(@NonNull Placement placement) {
    // App is paused after native ad got clicked
}

@Override
public void onResumeAfterAd(@NonNull Placement placement) {
    // Back to the app after clicking on the ad
}

// Image downloading logic
private void loadImage(ImageView imageView, String imageUrlString) {
    if (imageUrlString == null) {
        return;
    }

    Thread downloadThread = new Thread(() -> {
        final Bitmap bitmap = loadBitmap(imageUrlString);
        if (bitmap != null) {
            Handler h = new Handler(Looper.getMainLooper());
            h.post(() -> imageView.setImageBitmap(bitmap));
        } else {
            //failed
        }
    });
    downloadThread.start();
}

private static Bitmap loadBitmap(@NonNull String url) {
    Bitmap bitmap;
    try {
        InputStream in = new URL(url).openStream();
        bitmap = BitmapFactory.decodeStream(in);
    } catch (Exception t) {
        bitmap = null;
        //failed to decode bitmap
    }
    return bitmap;
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
private val nativeAdPlacement: NativeAdPlacement? = AATKit.createNativeAdPlacement("<PLACEMENT_NAME>", true)

override fun onResume() {
    super.onResume()
    // [IMPORTANT] Notify AATKit about activity lifecycle
    AATKit.onActivityResume(this)

    // Set placement listener to listen to the callbacks
    nativeAdPlacement?.listener = this
    // Request a native ad
    nativeAdPlacement?.reload()
}

override fun onPause() {
    // [IMPORTANT] Notify AATKit about activity lifecycle
    AATKit.onActivityPause(this)
    super.onPause()
}

// NativePlacementListener:
override fun onHaveAd(placement: Placement) {
    // Tha placement has loaded a new ad
    val nativeAd: NativeAdData = nativeAdPlacement.getNativeAd() ?: return
    // Prepare needed views
    val nativeAdView: ViewGroup = layoutInflater.inflate(android.R.layout.your_native_ad_layout, null) as ViewGroup
    val mainImageView: ImageView = nativeAdView.findViewById(android.R.id.mainImageView)
    val titleView: TextView = nativeAdView.findViewById(android.R.id.titleView)
    val iconView: ImageView = nativeAdView.findViewById(android.R.id.iconView)
    val descriptionView: TextView = nativeAdView.findViewById(android.R.id.adDescriptionView)
    val ctaView: TextView = nativeAdView.findViewById(android.R.id.CTA_view)
    val advertiserView: TextView = nativeAdView.findViewById(android.R.id.advertiser_textView)

    // Report Ad Space
    nativeAdPlacement.countAdSpace()
    // Ad Title
    titleView.text = nativeAd.title
    // Ad Icon
    loadImage(iconView, nativeAd.iconUrl)
    // Ad Main Image
    loadImage(mainImageView, nativeAd.imageUrl)
    // Ad Body
    descriptionView.text = nativeAd.description
    // Ad Identifier
    advertiserView.text = nativeAd.advertiser
    // Ad CTA Title
    ctaView.text = nativeAd.callToAction

    // Set the tracking view
    nativeAd.attachToLayout(nativeAdView, mainImageView, iconView, ctaView)

    // TODO: Present prepared ad on screen
}

override fun onNoAd(placement: Placement) {
    // The placement could not load a new ad
}

override fun onPauseForAd(placement: Placement) {
    // App is paused after native ad got clicked
}

override fun onResumeAfterAd(placement: Placement) {
    // Back to the app after clicking on the ad
}

// Image downloading logic
private fun loadImage(imageView: ImageView, imageUrlString: String?) {
    if (imageUrlString == null) {
        return
    }
    val downloadThread = Thread {
        val bitmap: Bitmap? = loadBitmap(imageUrlString)
        if (bitmap != null) {
            val h = Handler(Looper.getMainLooper())
            h.post { imageView.setImageBitmap(bitmap) }
        } else {
            //failed
        }
    }
    downloadThread.start()
}

private fun loadBitmap(url: String): Bitmap? {
    val bitmap: Bitmap?
    bitmap = try {
        val `in`: InputStream = URL(url).openStream()
        BitmapFactory.decodeStream(`in`)
    } catch (t: Exception) {
        null
        //failed to decode bitmap
    }
    return bitmap
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aatkit.gitbook.io/android-integration/formats/native-ad/basic-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
