Android HP4U Integration Guide

Android > HP4U

💡

Tip

  • While reading the documentation, make sure to download and experiment with our Demo App.
  • Stuck? Need a hand? Ask a question in our Support Forum.

Overview

Taboola's HP4U (Homepage For You) solution allows a publisher to display personalized recommendations on the homepage screen, increasing user engagement and boosting CTR (click-through rate).

Once the Taboola team has set up your HP4U configuration, follow the steps below to integrate the solution into your Android app.

🚧

In order to use HP4U, your homepage view must implement RecyclerView. At this time, other layouts are not supported.

📘

HP4U is part of Taboola's Mobile SDK, but requires additional, server-side configuration. (This is configured by the Taboola team during your initial onboarding.)

Project dependencies

  1. In your top-level build.gradle file, add the Taboola URL for Artifactory under allprojects > repositories:
buildscript {
    repositories {
        ...
    }
    dependencies {
        ...
    }
}

allprojects {
    repositories {
        ...
        maven {
            // Taboola:
            url 'https://taboolapublic.jfrog.io/artifactory/mobile-release'
        }
    }
}
  1. In your app module build.gradle file, add the Taboola and AndroidX Browser dependencies:
dependencies {

// Always required:
implementation 'com.taboola:<<androidSDKName>>:<<androidSDKVersion>>'
  
// To open the clicked item in a new *tab*:
implementation '<<androidXBrowser>>'

// For projects based on Java 1.7, use this version *instead*: 
// implementation 'androidx.browser:browser:1.0.0'
   
}

Project permissions

  1. Verify that the following permissions are present in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<!-- (Recommended) Allows Taboola SDK to use the 'IAB OM SDK': -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Initialize Taboola

  1. Create a TBLPublisherInfo object and initialize Taboola:
TBLPublisherInfo publisherInfo = new TBLPublisherInfo("<publisherName>").setApiKey("<apiKey>");
Taboola.init(publisherInfo);
Taboola.init(
    TBLPublisherInfo("<publisherName>").setApiKey("<apiKey>")
)
ParamTypeDescription
publisherNameStringA unique alphabetic String, as provided by Taboola during your initial onboarding. (Your ID might contain dashes, but not spaces.)

Example: "<<publisherID>>".
apiKeyStringA unique string of hexadecimal characters, as provided by Taboola during your initial onboarding. (Taboola will assign you 1 key per application.)

Example: "<<apiKey>>"

🚧

Important

  1. Initialization is required once per application. It should be done as early as possible - preferably in a subclass of Application.
  2. Failure to initialize successfully will result in Taboola recommendations not being displayed. Make sure that all paths within your application logic result in a successful initialization.

Create a TBLHomePage instance

In the onCreate or onCreateView method (of your Activity or Fragment):

  1. Each TBLHomePage instance uses a specific set of configurations. Use a TBLHomePageSettingsBuilder to create a TBLHomePageSettings instance with the relevant settings:
// In the `onCreate` or `onCreateView` method:

TBLHomePageSettingsBuilder tblHomePageSettingsBuilder = new TBLHomePageSettings.TBLHomePageSettingsBuilder(
                <PageUrl>,
                <sectionNames...>);
// In the `onCreate` or `onCreateView` method:

val tblHomePageSettings: TBLHomePageSettings?  =
    TBLHomePageSettings.TBLHomePageSettingsBuilder(
        <pageUrl>,
        <sectionNames...>).build()
// In the `onCreate` or `onCreateView` method:

val tblHomePageSettings: TBLHomePageSettings?  =
    TBLHomePageSettings.TBLHomePageSettingsBuilder(
        "https://www.example.com/",
        "News",
        "Sports",
        "Entertainment").build()
ParamTypeDescription
pageUrlStringA publicly accessible, canonical URL, with the same content as the home page view - e.g. "https://www.example.com/"

(Taboola crawls this URL for metadata and contextual data.)
sectionNamesString...The list of section names in the app that will use HP4U, as configured during the initial onboarding with Taboola.

The list is passed as a variable number of String arguments (varargs). See the example code snippet, provided above.
  1. (Optional) Set a fallback image, in case any thumbnail image fails to download:
TBLHomePageSettingsBuilder tblHomePageSettingsBuilder = new TBLHomePageSettings.TBLHomePageSettingsBuilder(
                <PageUrl>,
                <sectionNames...>)
                .setSwappedThumbnailFallbackImage(<swappedThumbnailFallbackImage>); // set fallback image
val tblHomePageSettings: TBLHomePageSettings  =
    TBLHomePageSettings.TBLHomePageSettingsBuilder(
        <pageUrl>,
        <sectionNames...>)
        .setSwappedThumbnailFallbackImage(<swappedThumbnailFallbackImage>) // set fallback image
        .build()
val tblHomePageSettings: TBLHomePageSettings =
    TBLHomePageSettings.TBLHomePageSettingsBuilder(
        "https://www.example.com/",
        "News",
        "Sports",
        "Entertainment")
        .setSwappedThumbnailFallbackImage(R.drawable.default_thumbnail_image) // set fallback image
        .build()
ParamTypeDescription
swappedThumbnailFallbackImageintThe fallback image resource ID

📘

If your fallback image also fails (or if you did not provide one), the Taboola SDK will substitute its own fallback image.

  1. Create a TBLHomePage instance to represent your app’s "home page", passing your TBLHomePageSettings instance (from above), and a TBLHomePageListener instance:
TBLHomePage homePage = Taboola.getHomePage(<homePageSettings>, <tblHomePageListener>);
homePage = Taboola.getHomePage(<tblHomePageSettings>, <tblHomePageListener>)
ParamTypeDescription
homePageSettingsTBLHomePageSettingsThe object (instantiated in step 1) that stores your HP4U settings.
tblHomePageListenerTBLHomePageListenerA listener for HP4U events.
See: TBLHomePageListener (below)
  1. Using the TBLHomePageListener instance that you passed above, implement the onHomePageItemClick event:
TBLHomePage homePage = Taboola.getHomePage(
    <homePageSettings>,
    new TBLHomePageListener() {
        @Override
        public boolean onHomePageItemClick(
            String sectionName,
            String itemId,
            String clickUrl,
            boolean isOrganic,
            String customData) {
                // Your click handling code goes here.
                // Return 'false' to ensure that Taboola does not handle the click event.      
            }
    });
homePage = Taboola.getHomePage(
    <homePageSettings>,
    object : TBLHomePageListener() {
        override fun onHomePageItemClick(
            sectionName: String?,
            itemId: String?,
            clickUrl: String?,
            isOrganic: Boolean,
            customData: String?
        ): Boolean {
            // Your click handling code goes here.
            // Return 'false' to ensure that Taboola does not handle the click event.  
        }
    }
)

🚧

Important

By default, Taboola SDK displays content in an external web view. To open organic content directly within your app, you must handle the onHomePageItemClick event.

For more information about event handling, see TBLHomePageListener (below).

Fetch Taboola content

  1. Once the onHomePageStatusChanged event is triggered by your TBLHomePageListenerand returns true, fetch Taboola content:
@Override
public void onHomePageStatusChanged(boolean status) {
    if (status) {
        homePage.fetchContent();
    }
}
override fun onHomePageStatusChanged(status: Boolean) {
    if (status) {
        homePage.fetchContent()
    }
}
  1. Attach your home page view layout to your TBLHomePage instance:
homePage.attach(<viewGroup>);
homePage.attach(<viewGroup>)
homePage.attach(binding.homepageRecyclerview)
ParamTypeDescription
viewGroupViewGroupYou must pass a RecyclerView. Other layouts are not supported.

Swap out items

Now that you have Taboola content, you can swap out the relevant items with personalized ones from Taboola.

For each item on the home page view, invoke the shouldSwapItemInSection method in your TBLHomePage instance.

🚧

Guidelines

  1. Invoke shouldSwapItemInSection in the onBindViewHolder method of your RecyclerView adapter.
  2. The shouldSwapItemInSection method must be invoked for all items in your home page view (including those items that are not expected to swap). Doing this enables Taboola to maintain an accurate map of your sections and items.
  3. The return value (true or false) indicates if the item will be swapped.

In the onBindViewHolder method of your RecyclerView.Adapter class:

boolean swappedPerformed = homePage.shouldSwapItemInSection(
        <linePosition>,
        <sectionName>,
        <lineView>,
        <titleView>,
        <contentView>,
        <thumbnailView>,
        <additionalViews>
    )
    if (!swappedPerformed) {
        // Item will not be swapped. 
        // You are responsible for the display of this item.
    }
val swappedPerformed: Boolean = homePage.shouldSwapItemInSection(
        <linePosition>,
        <sectionName>,
        <lineView>,
        <titleView>,
        <contentView>,
        <thumbnailView>,
        <additionalViews>
    )
    if (!swappedPerformed) {
        // Item will not be swapped. 
        // You are responsible for the display of this item.
    }
ParamTypeDescription
linePositionintThe row number of the RecyclerView cell.
sectionNameStringThe section name (as configured during the initial onboarding with Taboola).
lineViewViewA UI element that represents the cell.
titleView@Nullable TextView(Optional) The UI component that represents the title for the cell.
contentView@Nullable TextView(Optional) The UI component that represents the description for the cell.
thumbnailView@Nullable ImageView(Optional) The UI component that represents the thumbnail image for the cell.
additionalViews@Nullable AdditionalView(Optional) Used to pass additional, non-mandatory views.

Pass null for this param, unless instructed otherwise by Taboola.

📘

Return values

  • true => item will be swapped by Taboola (nothing further required from your side)
  • false => item will not be swapped (you are responsible for the display of this item)

When you call shouldSwapItemInSection, the Taboola SDK verifies the following:

i. Is this item a candidate to be swapped?
ii. Did the publisher submit the necessary Views in order to swap this item?
iii. Was Taboola able to fetch a personalized recommendation?

If all checks pass, the Taboola SDK returns true and updates the UI with a personalized recommendation.

If (for any reason) the item will not be swapped, the Taboola SDK returns false.

TBLHomePageListener

TBLHomePageListener supports the following events:

public abstract class TBLHomePageListener {

    public void onHomePageStatusChanged(boolean status) {}

    public void onHomePageError(String error, String sectionName) {}

    public boolean onHomePageItemClick(
        String sectionName, 
        String itemId,
        String clickUrl, 
        boolean isOrganic, 
        String customData) {}
}

📘

TBLHomePageListener is an abstract class. You can implement the events that you need, and ignore the others.

Events

onHomePageStatusChanged

When you create your TBLHomePage instance, the onHomePageStatusChanged event is triggered:

@Override
public void onHomePageStatusChanged(boolean status) {
    if (status) {
        homePage.fetchContent();
    }
}
override fun onHomePageStatusChanged(status: Boolean) {
    if (status) {
        homePage.fetchContent()
    }
}

🚧

Important

Do not fetch content until this event is triggered and returns true.

onHomePageError

If an error occurs while swapping an item, the onHomePageError event is triggered:

public void onHomePageError(String error, String sectionName) {}

📘

Possible values for error

"SWAP_FAILED_DUE_TO_MISSING_DATA"
"SWAP_FAILED_DUE_TO_MISSING_RECOMMENDATION"
"SWAP_FAILED_DUE_TO_MISSING_START_POSITION_ON_UNIT"
"FAILED_TO_RETRIEVE_RECOMMENDATION"

onHomePageItemClick

By default, Taboola SDK displays content for a clicked item in an external web view.

Use the onHomePageItemClick method to intercept the item click event, and open organic content directly within your app:

public boolean onHomePageItemClick(
  String sectionName, 
  String itemId,
  String clickUrl, 
  boolean isOrganic, 
  String customData) {
      // Your click handling code goes here.
      // Return 'false' to ensure that Taboola does not handle the click event.  
}

📘

Callback params

  • sectionName - The section name (as configured during the initial onboarding with Taboola).
  • itemId - The ID of the clicked item.
  • clickUrl - The Click URL of the clicked item.
  • isOrganic - Indicates if the clicked item is organic

    You can override the click behavior for organic content only.
    That said, at this time, HP4U content is always organic.

  • customData - Extra data passed from Taboola servers. (Can be null.)

📘

Return value

  • Return true to indicate that Taboola SDK should open the Click URL.
  • Return false to prevent Taboola SDK from opening the Click URL (allowing you to handle it).

Additional methods

This section describes some additional methods provided by TBLHomePage. Implementation of these methods is optional, and is not required for basic integration.

isActive

Returns true if your HP4U configuration is set to active - else, returns false:

homePage.isActive();

📘

If the need arises, you can ask the Taboola team to set your HP4U configuration to inactive. In that case, this method will return false.


See also: the onHomePageStatusChanged event (above).

setTBLHomePageListener

If you did not provide a listener when creating your TBLHomePage instance, you can use this method to set one:

homePage.setTBLHomePageListener(TBLHomePageListener tblHomePageListener);

setTargetType

By default, the target type for your TBLHomePage instance is "mix". If Taboola instructs you to use a different target type, use this method:

homePage.setTargetType(String targetType);

setUnifiedId

Use this method to set a unique ID for your HP4U instance:

homePage.setUnifiedId(String unifiedId);

💡

Tip

  • While reading the documentation, make sure to download and experiment with our Demo App.
  • Stuck? Need a hand? Ask a question in our Support Forum.