Ad Formats Android

Banners

Initialization

To display 320x50, 300x250, 728x90 and adaptive banners in your app, you must create an instance of the MyTargetView class. MyTargetView is a visual component (subclass of ViewGroup) that should be added to the app's screen.

Once instantiated, it needs to set your slotId.

The default is adaptive banner format. In this case, the banner is automatically stretched to the width of the screen while maintaining the proportions, and the height will be at least 50dip, but not more than 15% of the screen height. The system itself monitors screen resizing / flipping and resizes the banner accordingly.

It is possible to set the adSize property. In this case, the SDK will stop tracking changes in device orientation and resize the adaptive banner. In this case, when using adaptive banners, you need to track the changes yourself.

private MyTargetView adView;
 
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);
 
 
    // Enabling debug mode
    // MyTargetView.setDebugMode(true);
 
    // Create an instance of MyTargetView
    adView = new MyTargetView(this);
     
    // Set slot id
    adView.setSlotId(YOUR_SLOT_ID);
 
    // optional: if not set, banner will be adaptive
    adView.setAdSize(AdSize.ADSIZE_320x50);
}

Loading and displaying ads

The newly created and initialized MyTargetView instance must be added to the app's screen. To receive notifications (such as ad load succeeded, ad load failed, or ad clicked), you must create an instance of MyTargetView.MyTargetViewListener, set it as an event listener, and then start loading ad. After ad has loaded successfully, you can start displaying ad.

private MyTargetView adView;
 
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);
 
 
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.activityLayout);
 
    // Create an instance of MyTargetView
    adView = new MyTargetView(this);
     
    // Set slot id
    adView.setSlotId(YOUR_SLOT_ID);
 
    // Set the LayoutParams
    adViewLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    adViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    adView.setLayoutParams(adViewLayoutParams);
     
    // Set the event listener
    adView.setListener(new MyTargetView.MyTargetViewListener()
    {
        @Override
        public void onLoad(MyTargetView myTargetView)
        {
            // The ad is successfully loaded. Start displaying ad
            layout.addView(adView);
        }
 
        @Override
        public void onNoAd(String reason, MyTargetView myTargetView)
        {  
        }
 
        @Override
        public void onShow(MyTargetView myTargetView)
        {
        }
 
        @Override
        public void onClick(MyTargetView myTargetView)
        {
        }
    });
     
    // Start loading ad
    adView.load();
}
     
@Override
protected void onDestroy()
{
    if (adView != null) adView.destroy();
    super.onDestroy();
}

Set MyTargetView in XML

It is possible to set MyTargetView as part of XML layout.

<com.my.target.ads.MyTargetView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/view_ad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:myTarget_isRefreshAd="false"  // turning off banner rotation
    app:myTarget_adSize="banner_320x50" // set format, possible values: banner_320x50, banner_30x250, banner_728x90, adaptive
    app:myTarget_slotId="7250"> // slot number
</com.my.target.ads.MyTargetView>

Rotation

Ads are rotated every 60 seconds. You can disable automatic ad rotation by specifying the optional isRefreshAd parameter when initializing the instance. Rotation is only available for 320x50 and 728x90 formats.

// Disable automatic ad rotation
adView.setRefreshAd(false);
Banner 320x50

Interstitial Ads

Initialization

To display interstitial ad in your app, create an instance of the InterstitialAd class. You must specify your slotId when creating an instance.

private InterstitialAd ad;
 
private void initAd()
{
    // Enabling debug mode
    // MyTargetManager.setDebugMode(true);
     
    // Create an instance of InterstitialAd
    ad = new InterstitialAd(YOUR_SLOT_ID, this);
}

Loading ads

To receive notifications (such as ad load succeeded, ad load failed, or ad clicked), you must create an object that implements the InterstitialAd.InterstitialAdListener interface and set it as an event listener. Then you can start loading ad.

private InterstitialAd ad;
 
private void initAd()
{
    // Create an instance of InterstitialAd
    ad = new InterstitialAd(YOUR_SLOT_ID, this);
    // Set the event listener
    interstitialAd.setListener(new InterstitialAd.InterstitialAdListener()
    {
        @Override
        public void onLoad(InterstitialAd ad)
        {
        }
 
        @Override
        public void onNoAd(String reason, InterstitialAd ad)
        {
        }
  
        @Override
        public void onClick(InterstitialAd ad)
        {
        }
  
        @Override
        public void onDisplay(InterstitialAd ad)
        {
        }
  
        @Override
        public void onDismiss(InterstitialAd ad)
        {
        }
 
 
        @Override
        public void onVideoCompleted(InterstitialAd ad)
        {
        }
    });
     
    // Start loading ad
    ad.load();
}

Displaying ads

After the ad has loaded successfully, you can start displaying interstitial ad.

@Override
public void onLoad(InterstitialAd ad)
{
    // Start displaying
    // in a separate Activity
    ad.show();   
}
Interstitial Ads Banner

Rewarded video

Initialization

To display full-screen ads in your application, you must create an instance of the InterstitialAd class. To create an instance, you must specify your slotId.

private RewardedAd ad;
 
private void initAd()
{
    // Turn on debug mode
    // MyTargetManager.setDebugMode(true);
     
    // Create instance of RewardedAd
    ad = new RewardedAd(YOUR_SLOT_ID, this);
}

Loading ads

To receive notifications (such as ad load succeeded, ad load failed, reward earned, ad clicked etc.), you must set a listener, which implements the RewardedAd.RewardedAdListener interface, on the RewardedAd instance. Then you can start loading ad.

private RewardedAd ad;
 
private void initAd()
{
    // Creating RewardedAd instance
    ad = new RewardedAd(YOUR_SLOT_ID, this);
    // Set listener
    ad.setListener(new RewardedAd.RewardedAdListener()
    {
        @Override
        public void onLoad(RewardedAd ad)
        {
        }
 
        @Override
        public void onNoAd(String reason, RewardedAd ad)
        {
        }
  
        @Override
        public void onClick(RewardedAd ad)
        {
        }
  
        @Override
        public void onDisplay(RewardedAd ad)
        {
        }
  
        @Override
        public void onDismiss(RewardedAd ad)
        {
        }
  
        @Override
        void onReward(@NonNull Reward reward, @NonNull RewardedAd ad)
        {
        }
    });
     
    // Start loading
    ad.load();
}

Displaying ads

After the ad has loaded successfully, you can start displaying rewarded ad.

@Override
public void onLoad(RewardedAd ad)
{
    // Start showing
    ad.show();
}

Reward

When reward is received, callback onReward will be called on interface with Reward object containing field type

Reward.type;

Native Ads

The myTarget SDK provides the ability to display ads in your app using native visual components. The SDK loads the ad and gives the app an ad model with specific properties and methods for counting impressions and handing clicks. The API also provides build-in visual component that you can use in your app, instead of creating your own.

Initialization

To display native ads in your app, you must create an instance of the NativeAd class and specify your slotId.

private NativeAd ad;
 
private void initAd()
{
    // Enabling debug mode
    // MyTargetManager.setDebugMode(true); 
 
 
    // Create an instance of NativeAd
    ad = new NativeAd(YOUR_SLOT_ID, this);
}

Loading ads

To receive notifications (such as ad load succeeded, ad load failed, or ad clicked), you must create an instance of NativeAdListener and set it as an event listener. Then you can load the ad.

private NativeAd ad;
 
private void initAd()
{
    // Create an instance of NativeAd
    ad = new NativeAd(YOUR_SLOT_ID, this);
     
    // Set the event listener
    ad.setListener(new NativeAd.NativeAdListener()
    {
        @Override
        public void onLoad(NativePromoBanner banner, NativeAd ad)
        {
        }
 
        @Override
        public void onNoAd(String reason, NativeAd ad)
        {
        }
 
        @Override
        public void onClick(NativeAd ad)
        {
        }
  
        @Override
        public void onShow(NativeAd ad)
        {
        }
 
 
        @Override
        public void onVideoPlay(NativeAd ad)
        {
        }
 
 
        @Override
        public void onVideoPause(NativeAd ad)
        {
        }
 
 
        @Override
        public void onVideoComplete(NativeAd ad)
        {
        }
    });
         
    // Start loading ad
    ad.load();
}

Autoloading images and video

By default, images and videos are preloaded. You can turn off the automatic loading of images and videos, but keep in mind that downloading them will take extra time, which will create an additional delay in displaying ads in your application.


ad.setCachePolicy(CachePolicy.NONE);
ad.load();   
Valid values are CachePolicy.ALL (default), CachePolicy.IMAGE, CachePolicy.VIDEO, CachePolicy.NONE.

If preloading is enabled, then the corresponding images will be loaded and cached in parallel with the loading of the main data of the advertising banner.

If the preloading of images is turned off, they will be asynchronously and automatically loaded when the registerView method is called. No additional action required.

Successful asset loading notifications

It is possible to put a listener to receive notifications about the successful loading of image and icon image files in case of automatic loading.

ad.setMediaListener(new NativeAdMediaListener() {
            @Override
            public void onIconLoad(@NonNull NativeAd ad)
            {
                // icon upload success notification
            }
 
            @Override
            public void onImageLoad(@NonNull NativeAd ad)
            {
                // notification of successful upload of the main image
            }
        });
ad.load();  

Displaying ads

After successfully loading the ad, you can use the properties of the banner object to initialize your visual component. Which properties are available depends on what is being advertised, i.e. they differ for apps and websites. To display main image, carousel and video playback, you must use an instance of MediaAdView class from myTarget SDK. Visual component should be added to com.my.target.nativeads.views.NativeAdContainer.

Visual component's elements should have id's provided with myTarget SDK

After initializing a visual component, use the registerView method to register it with the NativeAd instance. If you are going to use the same visual component to display other ads, you must first call the unregisterView method on the current NativeAd instance before calling registerView on another NativeAd instance. Impressions and clicks are processed automatically, and the application should not block or capture user touch events on this visual component. The properties available are described below, and examples of initializing visual component.

@Override
public void onLoad(NativePromoBanner banner, NativeAd ad)
{  
    // Ad title
    String title = banner.getTitle();
    // Main text
    String description = banner.getDescription();
    // Age limit. May be null
    String ageRestrictions = banner.getAgeRestrictions();
    // Disclaimer. May be null
    String disclaimer = banner.getDisclaimer();
    // "Advertising" label text
    String advertisingLabel = banner.getAdvertisingLabel();
    // Icon
    ImageData icon = banner.getIcon();
    // Call-to-action text for the button
    String ctaText = banner.getCtaText();
    // Properties available only for ads promoting apps
    if (banner.getNavigationType().equals(NavigationType.STORE))
    {
        // App rating (0-5)
        float rating = banner.getRating();
        // Number of votes
        int votes = banner.getVotes();
        // App category
        String category = banner.getCategory();
        // App subcategory
        String subcategory = banner.getSubcategory();
    }
    // Properties available only for ads promoting websites
    else if (banner.getNavigationType().equals(NavigationType.WEB))
    {
        // Website domain
        String domain = banner.getDomain();
    }
     
    // Use properties to build your visual component
 
    Context context = YourActivity.this;
    LinearLayout adViewLayout = new LinearLayout(context);
    adViewLayout.setId(R.id.nativeads_ad_view);
    TextView titleView = new TextView(context);
    titleView.setId(R.id.nativeads_title);
    titleView.setText(title);
    adViewLayout.addView(titleView);
    TextView descriptionView = new TextView(context);
    descriptionView.setId(R.id.nativeads_description);
    titleView.setText(description);
    adViewLayout.addView(descriptionView);
    Button btn = new Button(context);
    btn.setId(R.id.nativeads_call_to_action);
    btn.setText(ctaText);
    adViewLayout.addView(btn);
     
    // Create an instance of MediaAdView
    MediaAdView mediaView = NativeViewsFactory.getMediaAdView(context);
    mediaView.setId(R.id.nativeads_media_view);
    // Create an instance of IconAdView
    IconAdView iconView = new IconAdView(context);
    mediaView.setId(R.id.nativeads_icon);
 
    // If you have enabled autoloading of images, you can assign the loaded icon here: iconView.setImageBitmap(image.getBitmap());
     
    adViewLayout.addView(mediaView);
    adViewLayout.addView(iconView);
 
 
    // Create container
    NativeAdContainer nativeAdContainer = new NativeAdContainer(context);
    // Add view to container
    nativeAdContainer.addView(adViewLayout);
         
    // Register the view
    ad.registerView(adViewLayout);
  
    // Add it to the layout
    mainLayout.addView(nativeAdContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

AdChoices icon

The myTarget SDK automatically adds an AdChoices icon to each visual component. By default, the icon is added to the top-right corner of the visual component, but you can choose your preferred corner with the setAdChoicesPlacement(int placement) method:

...
ad.setAdChoicesPlacement(AdChoicesPlacement.TOP_RIGHT);
ad.load(); 

Manual setting of AdChoices

If you want to set your own image for AdChoices, you have to use the NativeAdChoicesView class and pass the image there using the setImageBitmap() or setImageDrawable() methods.

...
NativeAdChoicesView myAdChoicesView = createMyAdChoicesView(); // Creating your own NativeAdChoicesView
myAdChoicesView.setImageBitmap(bitmap);
myAdChoicesView.setImageDrawable(drawable);
...
In case manual positioning of AdChoicesView (setting gravity, margins) within its View is required to show native ads, AdChoicesPlacement.MANUAL must be specified.

...
ad.setAdChoicesPlacement(AdChoicesPlacement.MANUAL);
ad.load(); 

Customizing the AdChoices button

The developer can draw the AdChoices button himself as he wants, but in this case the NativeAd must be set to AdChoicesPlacement.DRAWING_MANUAL property. You also need to call the ad.handleAdAdChoicesClick(context) method to handle clicking on the AdChoices.

...
ad.setAdChoicesPlacement(AdChoicesPlacement.DRAWING_MANUAL);
ad.load();
...
customAdChoicesView.setOnClickListener(v->{
    ad.handleAdChoicesClick(context)
})
To get the AdChoices icon, you can call the ad object directly or use the NativeAdChoicesListener, the listener must be set before the ad is loaded.

//getting an AdChoises icon through a variable
ad.getBanner().getAdChoicesIcon();
...
//getting an AdChoises icon through the listener
ad.setAdChoicesListener(new NativeAd.NativeAdChoicesListener() {
    @Override
    public void onAdChoicesIconLoad(@Nullable ImageData imageData, boolean success, @NonNull NativeAd ad)
    {
        customAdChoicesView.setImageBitmap(imageData.getBitmap)
    }
});

Customizing the rendering of AdChoices options

To change the design of drawing AdChoices options it's necessary in the NativeAd constructor to pass an object implementing the MenuFactory interface, which in turn should return an object implementing the Menu interface.

MenuFactory menuFactory = new MenuFactory()
    {
        @Override
        @NonNull public Menu createMenu()
        {
            return new Menu()
            {
                @Override
                public void setListener(@Nullable Listener listener)
                {
                    //the listener that needs to call the onActionClick(menuAction) method when you click on the UI element that was drawn with the corresponding menuAction title
                }
 
                @Override
                public void addAction(@NonNull MenuAction menuAction)
                {
                    // this is an object that contains the header and option type of AdChoices, these objects should be used when drawing
                }
 
                @Override
                public void present(@NonNull Context context)
                {
                    // this method is called when you want to display AdChoices options with those menuActions that were previously obtained from the addAction() method
                }
 
                @Override
                public void dismiss()
                {
                    // this method is called when it is necessary to close the rendering of the AdChoices options
                }
            };
        }
    };
...
ad = new NativeAd(YOUR_SLOT_ID, menuFactory, this);
ad.load();

Managing ad closures

In order to receive notifications about ad closures and manage ad closures, you need to pass an object that implements the NativeAdChoicesOptionListener interface. The interface contains several methods.
  • boolean shouldCloseAutomatically() - informs SDK whether to automatically close ads. If the method returns true, the SDK will automatically hide the ads. If false, the ability to hide is left to the developer.
  • onCloseAutomatically() - notifies the developer that the ad has been automatically hidden by the SDK. So, this method will be called only if shouldCloseAutomatically returns true.
  • closeIfAutomaticallyDisabled() - notifies the developer that he needs to hide the ads himself. So this method will be called only if shouldCloseAutomatically returns false.

NativeAd.NativeAdChoicesOptionListener adChoicesOptionListener = new NativeAd.NativeAdChoicesOptionListener()
{
    @Override
    public boolean shouldCloseAutomatically()
    {
        return false;
    }
 
    @Override
    public void onCloseAutomatically(@NonNull NativeBannerAd ad)
    {
 
    }
 
    @Override
    public void closeIfAutomaticallyDisabled(@NonNull NativeBannerAd ad)
    {
 
    }
};
         
ad.setAdChoicesOptionListener(adChoicesOptionListener);

Setting clickable area

In the example above, the visual component is registered using the registerView(View view) method. In this case, the entire area of the visual component is clickable. MyTarget SDK provides the ability to register list of visual components that can be clicked. To do this, use the registerView(View view, List <View> clickableViews) method:

@Override
public void onLoad(NativePromoBanner banner, NativeAd ad)
{
    ...
    ...
    ...
     
    // Create an array of clickable visual components, titleView and cta button
    ArrayList<View> clickableViews = new ArrayList<>();
    clickableViews.add(titleView);
    clickableViews.add(btn);
    // Register the view with clickable titleView and button
    ad.registerView(adViewLayout, clickableViews);
  
    // Add it to the layout
    mainLayout.addView(adViewLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

Using built-in visual component

MyTarget SDK provides a built-in custom visual component, the appearance of which you can customize to the design of your application.

The following are examples and the properties that are available for customization.

We give some examples below and describe the settings available.
NativeAdView

public void onLoad(NativePromoBanner banner, NativeAd ad)
{
    // Create visual component
    NativeAdView nativeAdView = NativeViewsFactory.getNativeAdView(ad, YourActivity.this);
     
    // Available inner components
    TextView advLabelView = nativeAdView.getAdvertisingTextView();
    TextView ageRestrictionView = nativeAdView.getAgeRestrictionTextView();
    TextView disclaimerView = nativeAdView.getDisclaimerTextView();
    TextView titleView = nativeAdView.getTitleTextView();
    TextView descriptionView = nativeAdView.getDescriptionTextView();  
    Button ctaBtn = nativeAdView.getCtaButtonView();
    TextView votesView = nativeAdView.getVotesTextView();
    StarsRatingView starsRatingView = nativeAdView.getStarsRatingView();
    TextView domainView = nativeAdView.getDomainOrCategoryTextView();
    MediaAdView mediaView = nativeAdView.getMediaAdView();
    IconAdView iconView = nativeAdView.getIconImageView();
 
    // Create container for creative
    NativeAdContainer nativeAdContainer = new NativeAdContainer(context);
    // Add ad creative to container
    nativeAdContainer.addView(nativeAdView);
     
    // Register visual component
    ad.registerView(nativeAdContainer);
     
    // Add to screen
    mainLayout.addView(nativeAdContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

Loading multiple banners

The myTarget SDK provides the class NativeAdLoader, which allows you to load from 1 to 20 banners per one request. For NativeAdLoader, you can configure all the same settings that are available for customization in NativeAd (for example, user's gender and age, autoloading images and videos). There is no guarantee that the number of banners specified in the COUNT parameter will be loaded - this parameter indicates the maximum number of banners that you want to receive.

// Enabling debug mode
// MyTargetManager.setDebugMode(true); 
 
 
// Create an instance of NativeAdLoader
NativeAdLoader nativeAdLoader = NativeAdLoader.newLoader(YOUR_SLOT_ID, COUNT, this);
 
// Set the OnLoad callback and loading ads
nativeAdLoader.setOnLoad(new OnLoad()
{
   @Override
   public void onLoad(@NonNull List<NativeAd> ads)
   {
      for (NativeAd ad : ads)
      {
        // Set the event listener
        ad.setListener(nativeAdListener);
         
        NativePromoBanner promoBanner = ad.getBanner();
        // The same code as in onLoad method of NativeAdListener interface
      }
   }
}).load();
The resulting array will contain from 0 to COUNT instances of NativeAd - each of them contains already loaded NativePromoBanner and with each of them it is necessary to work the same as described in this documentation above, starting from the onLoad method.

Native Banners

myTarget SDK provides the ability to display ads in your application using its own visual components. The SDK downloads data and provides the application with an ad model with specific properties to populate the visual component, as well as methods for counting impressions and processing clicks. The SDK also provides a built-in custom visual component that you can use in your application, instead of creating your own.

The native banner does not support MediaAdView and therefore cannot display media content (video, cards, large image).

Initialization

To display native banners in your application, you must create an instance of the NativeBannerAd class. To create an instance of NativeBannerAd, you must specify your slotId.

private NativeBannerAd ad;
 
private void initAd()
{
    // Turn on debug mode
    // MyTargetManager.setDebugMode(true); 
 
 
    // Creating instance of NativeBannerAd
    ad = new NativeBannerAd(YOUR_SLOT_ID, this);
}

Loading ads

To receive notifications (such as a successful data download or a download error, click on an advertisement), you must create an instance of NativeBannerAdListener and set it as an event listener, after which you can start the data download.

private NativeBannerAd ad;
 
private void initAd()
{
    // Creating instance of NativeBannerAd
    ad = new NativeBannerAd(YOUR_SLOT_ID, this);
     
    // add listener
    ad.setListener(new NativeBannerAd.NativeBannerAdListener()
    {
        @Override
        public void onLoad(NativeBanner banner, NativeBannerAd ad)
        {
        }
 
        @Override
        public void onNoAd(String reason, NativeBannerAd ad)
        {
        }
 
        @Override
        public void onClick(NativeBannerAd ad)
        {
        }
  
        @Override
        public void onShow(NativeBannerAd ad)
        {
        }
    });
         
    // Start loading data
    ad.load();
}

Autoloading images

By default, all banner images are loaded and cached. You can turn off the automatic loading of images, but keep in mind that they will take extra time to load, which will create an additional delay in displaying ads in your application.

ad.setCachePolicy(CachePolicy.NONE);
ad.load();
Valid values are CachePolicy.ALL (by default), CachePolicy.IMAGE, CachePolicy.NONE.

If preloading is enabled, then the corresponding images will be loaded and cached in parallel with the loading of the main data of the advertising banner.

If the preloading of images is turned off, they will be asynchronously and automatically loaded when the registerView method is called. No additional action required.

Successful asset loading notifications

It is possible to put a listener to receive notifications about the successful loading of the icon image file in case of automatic loading.

ad.setMediaListener(new NativeBannerAdMediaListener() {
            @Override
            public void onIconLoad(@NonNull NativeBannerAd ad)
            {
                // icon upload success notification
            }
        });
ad.load(); 

Displaying ads

After successfully loading the data, you can use the properties of the resulting banner instance to populate your visual component. The availability of properties depends on the type of advertised object - for applications and sites they differ.

To display the icon, use the IconAdView provided by the SDK.

Visual components (both standard and proprietary) should be placed inside the NativeAdContainer container.
At the same time, both the component itself and the container can be passed to the registerView method.
When creating the container, the visual component adView will be added as a subview to the container and stretched to fit the container.

Elements of the visual component must be assigned the corresponding id supplied with the SDK

After filling in the visual component, you must register it with the NativeAd instance using the registerView method. If you intend to use the same visual component to display other advertisements, you must first call the unregisterView method on the current NativeAd instance before calling registerView on the other instance. Processing impressions and clicks is carried out automatically, while the application should not block or intercept user events on this visual component. Available properties are described below and examples of filling visual components for various types of advertised objects are given.

@Override
public void onLoad(NativeBanner banner, NativeBannerAd ad)
{
    // Ad Title
String title = banner.getTitle ();
// Age limit. May be null
String ageRestrictions = banner.getAgeRestrictions ();
// Disclaimer. May be null
String disclaimer = banner.getDisclaimer ();
// The text of the label "Advertising"
String advertisingLabel = banner.getAdvertisingLabel ();
 
 
// Icon
ImageData icon = banner.getIcon ();
// The action text for the button
String ctaText = banner.getCtaText ();
// Properties Available Only For Ads Promoting Applications
if (banner.getNavigationType (). equals (NavigationType.STORE))
{
// Application Rating (0-5)
float rating = banner.getRating ();
// Number of ratings
int votes = banner.getVotes ();
}
// Properties Available Only For Ads Promoting Websites
else if (banner.getNavigationType (). equals (NavigationType.WEB))
{
// site domain
String domain = banner.getDomain ();
}
 
// An example of filling a visual component
Context context = YourActivity.this;
LinearLayout adViewLayout = new LinearLayout (context);
adViewLayout.setId (R.id.nativeads_ad_view);
TextView titleView = new TextView (context);
titleView.setId (R.id.nativeads_title);
titleView.setText (title);
adViewLayout.addView (titleView);
Button btn = new Button (context);
btn.setId (R.id.nativeads_call_to_action);
btn.setText (ctaText);
adViewLayout.addView (btn);
 
IconAdView iconView = new IconAdView(context);
mediaView.setId (R.id.nativeads_icon);
 
adViewLayout.addView (iconView);
 
 
// Create a creative container
NativeAdContainer nativeAdContainer = new NativeAdContainer (context);
// Add ad creative to container
nativeAdContainer.addView (adViewLayout);
 
// Register the visual component
ad.registerView (adViewLayout);
 
// Add to the screen
mainLayout.addView (nativeAdContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

AdChoices icon

The myTarget SDK automatically adds an adChoices icon to each visual component. By default, the icon is added to the top-right corner of the visual component, but you can choose your preferred corner with the adChoicesPlacement property:

...
ad.setAdChoicesPlacement(AdChoicesPlacement.TOP_RIGHT);
ad.load(); 

Manual setting of AdChoices

If you want to set your own image for AdChoices, you have to use the NativeAdChoicesView class and pass the image there using the setImageBitmap() or setImageDrawable() methods.

...
NativeAdChoicesView myAdChoicesView = createMyAdChoicesView(); // creating own NativeAdChoicesView
myAdChoicesView.setImageBitmap(bitmap);
myAdChoicesView.setImageDrawable(drawable);
...
In case manual positioning of AdChoicesView (setting gravity, margins) within its View is required to show native ads, AdChoicesPlacement.MANUAL must be specified.

...
ad.setAdChoicesPlacement(AdChoicesPlacement.MANUAL);
ad.load(); 

Customizing the AdChoices button

The developer can draw the AdChoices button himself as he wants, but in this case the AdChoicesPlacement.DRAWING_MANUAL property must be set for NativeBannerAd. You also need to call the ad.handleAdAdChoicesClick(context) method to handle clicking on the AdChoices.

...
ad.setAdChoicesPlacement(AdChoicesPlacement.DRAWING_MANUAL);
ad.load();
...
customAdChoicesView.setOnClickListener(v->{
ad.handleAdChoicesClick(context)
})
To get the AdChoices icon, you can call the ad object directly or use the NativeAdChoicesListener, the listener must be set before the ad is loaded.

//getting an AdChoises icon through a variable
ad.getBanner().getAdChoicesIcon();
...
//getting an AdChoises icon through the listener
ad.setAdChoicesListener(new NativeBannerAd.NativeBannerAdChoicesListener() {
    @Override
    public void onAdChoicesIconLoad(@Nullable ImageData imageData, boolean success, @NonNull NativeAd ad)
    {
        customAdChoicesView.setImageBitmap(imageData.getBitmap)
    }
});

Customizing the rendering of AdChoices options

To change the design of drawing AdChoices options it's necessary in the NativeBannerAd constructor to pass an object implementing the MenuFactory interface, which in turn should return an object implementing the Menu interface.

MenuFactory menuFactory = new MenuFactory()
    {
        @Override
        @NonNull public Menu createMenu()
        {
            return new Menu()
            {
                @Override
                public void setListener(@Nullable Listener listener)
                {
                    //the listener that needs to call the onActionClick(menuAction) method when you click on the UI element that was drawn with the corresponding menuAction title
                }
 
                @Override
                public void addAction(@NonNull MenuAction menuAction)
                {
                    // this is an object that contains the header and option type of AdChoices, these objects should be used when drawing
                }
 
                @Override
                public void present(@NonNull Context context)
                {
                    // this method is called when you want to display AdChoices options with those menuActions that were previously obtained from the addAction() method
                }
 
                @Override
                public void dismiss()
                {
                    // this method is called when it is necessary to close the rendering of the AdChoices options
                }
            };
        }
    };
...
ad = new NativeBannerAd(YOUR_SLOT_ID, menuFactory, this);
ad.load();

Managing ad closures

In order to receive notifications about ad closures and manage ad closures, you need to pass an object that implements the NativeBannerAdChoicesOptionListener interface. The interface contains several methods.

  • boolean shouldCloseAutomatically() - informs SDK whether to automatically close ads. If the method returns true, the SDK will automatically hide the ads. If false, the ability to hide is left to the developer.
  • onCloseAutomatically() - notifies the developer that the ad has been automatically hidden by the SDK. So, this method will be called only if shouldCloseAutomatically returns true.
  • closeIfAutomaticallyDisabled() - notifies the developer that he needs to hide the ads himself. So this method will be called only if shouldCloseAutomatically returns false.

NativeBannerAd.NativeBannerAdChoicesOptionListener adChoicesOptionListener = new NativeBannerAd.NativeBannerAdChoicesOptionListener()
{
    @Override
    public boolean shouldCloseAutomatically()
    {
        return false;
    }
 
    @Override
    public void onCloseAutomatically(@NonNull NativeBannerAd ad)
    {
 
    }
 
    @Override
    public void closeIfAutomaticallyDisabled(@NonNull NativeBannerAd ad)
    {
 
    }
};
         
ad.setAdChoicesOptionListener(adChoicesOptionListener);

Setting clickable area

In the above example, the visual component is registered using the registerView (View view) method. In this case, the entire area of the visual component is clickable. The MyTarget SDK provides the ability to specify specific visual components that clicks will be tracked. To do this, use the registerView method (View view, List <View> clickableViews):

@Override
public void onLoad(NativeBanner banner, NativeBannerAd ad)
{
    ...
    ...
    ...
     
    // Create an array of clickable visual components, a title and a call to action button
    ArrayList<View> clickableViews = new ArrayList<>();
    clickableViews.add(titleView);
    clickableViews.add(btn);
    // Register the visual component, with a clickable title and a call to action button
    ad.registerView(adViewLayout, clickableViews);
  
    // Add to the screen
    mainLayout.addView(adViewLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

Using a built-in visual component

MyTarget SDK provides a built-in custom visual component, the appearance of which you can customize to the design of your application.

The following are examples and the properties that are available for customization.

NativeBannerAdView

public void onLoad(NativeBanner banner, NativeBannerAd ad)
{
    // Create a visual component
NativeBannerAdView nativeBannerAdView = NativeViewsFactory.getNativeBannerAdView (YourActivity.this);
nativeBannerAdView.setupView(banner);
 
// Customizable internal visual components
TextView advLabelView = nativeBannerAdView.getAdvertisingTextView ();
TextView ageRestrictionView = nativeBannerAdView.getAgeRestrictionTextView ();
TextView disclaimerView = nativeBannerAdView.getDisclaimerTextView ();
TextView titleView = nativeBannerAdView.getTitleTextView ();
Button ctaBtn = nativeBannerAdView.getCtaButtonView ();
TextView votesView = nativeBannerAdView.getVotesTextView ();
StarsRatingView starsRatingView = nativeBannerAdView.getStarsRatingView ();
TextView domainView = nativeBannerAdView.getDomainOrCategoryTextView ();
IconAdView iconView = nativeBannerAdView.getIconImageView ();
 
// Create a creative container
NativeAdContainer nativeAdContainer = new NativeAdContainer (context);
// Add ad creative to container
nativeAdContainer.addView (nativeBannerAdView);
 
// Register the visual component
ad.registerView (nativeAdContainer);
 
// Add to the screen
mainLayout.addView (nativeAdContainer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

Loading of multiple banners

MyTarget SDK provides the NativeBannerAdLoader class, which makes it possible to load from 1 to 20 banners in one request. For NativeBannerAdLoader, you can configure all the same parameters that are available for setting in NativeBannerAd (for example, gender and age parameters of the user, autoload images and videos). myTarget SDK does not guarantee that the number of banners specified in the COUNT parameter will be loaded - this parameter indicates the maximum number of banners that you want to receive.

// Turn on debug mode
// MyTargetManager.setDebugMode(true); 
 
// Creating NativeBannerAdLoader
NativeBannerAdLoader nativeBannerAdLoader = NativeBannerAdLoader.newLoader(YOUR_SLOT_ID, COUNT, this);
 
// Install OnLoad callback and load banners
nativeBannerAdLoader.setOnLoad(new OnLoad()
{
   @Override
   public void onLoad(@NonNull List<NativeBannerAd> ads)
   {
      for (NativeBannerAd ad : ads)
      {
        // add listener
        ad.setListener(nativeBannerAdListener);
         
        NativeBanner banner = ad.getBanner();
      }
   }
}).load();
The resulting array will contain from 0 to COUNT NativeBannerAd objects - each of them contains an already loaded NativeBanner and you need to work with each of them in the same way as described in this documentation above, starting with calling the onLoad method.

In-stream video

The myTarget SDK provides the ability to show in-stream video ads in your app, while watching a video. Ads can be shown before (preroll), during (midroll) and after (postroll) the video. The SDK loads the data and allows the application to show ads in both its video player and in the application's player.

Initialization

To display a promotional video in your application, you must create an instance of the class InstreamAd. To create an InstreamAd instance, you must specify your slotId. For each video in the application, you need to create your own copy of the class InstreamAd.

private InstreamAd ad;
 
private void initAd()
{
    
    // Enable debug mode
    // MyTargetManager.setDebugMode(true);
    // Instantiate InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
}

Using the application player

To play ads in the player application, it must implement the interface InstreamAdPlayer and notify the installed listener AdPlayerListener.

To use your player, call the setPlayer(InstreamAdPlayer player) method on the InstreamAd instance you created.

private InstreamAd ad;
 
private void initAd()
{
    // Instantiate InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
     
    // Install the player
    ad.setPlayer(YOUR_PLAYER);
}

AdChoices button

The developer must draw the AdChoices button himself as he needs it. Also, the ad.handleAdAdChoicesClick(context) method must be called to handle clicking on the adchoices. By default, the AdChoices button is not displayed for InstreamAd.

customAdChoicesView.setOnClickListener(v->
{
    ad.handleAdChoicesClick(context)
})

Customizing the rendering of AdChoice options

To change the design of displaying AdChoices options it is necessary to pass the object implementing the MenuFactory interface in the InstreamAd constructor, which in turn should return the object implementing the Menu interface. If the parameter is not passed to SDK, by default it will display the standard implementation of displaying AdChoices menu options.

MenuFactory menuFactory = new MenuFactory()
    {
        @Override
        @NonNull public Menu createMenu()
        {
            return new Menu()
            {
                @Override
                public void setListener(@Nullable Listener listener)
                {
                    //the listener that needs to call the onActionClick(menuAction) method when you click on the UI element that was drawn with the corresponding menuAction title
                }
 
                @Override
                public void addAction(@NonNull MenuAction menuAction)
                {
                    // this is an object that contains the header and option type of AdChoices, these objects should be used when drawing
                }
 
                @Override
                public void present(@NonNull Context context)
                {
                    // this method is called when you want to display AdChoices options with those menuActions that were previously obtained from the addAction() method
                }
 
                @Override
                public void dismiss()
                {
                    // this method is called when it is necessary to close the rendering of the AdChoices options
                }
            };
        }
    };
...
ad = new InstreamAd(YOUR_SLOT_ID, menuFactory, this);
ad.load();

Interface InstreamAdPlayer

Interface methods are invoked InstreamAdPlayer instance InstreamAd. You do not need to call them yourself.
1. The duration of the promotional video

float getAdVideoDuration();

2. The current position of the promotional video. The method is called multiple times during ad video playback and should return the actual value in seconds.

float getAdVideoPosition();

3. Sets a listener to the player

void setAdPlayerListener(AdPlayerListener listener);

4. Visual representation of the player, usually "this".

View getView();

5. Sets the volume from 0 to 1.

void setVolume(float volume);
6. Starts playback of the promotional video.
  • uri - the path to the video
  • width - video width in pixels
  • height - video height in pixels

void playAdVideo(Uri uri, int width, int height);
7. Pauses the playback of the advertising video.ht - height of video in pixels

void pauseAdVideo();

8. Resumes playing the promotional video.

void resumeAdVideo();

9. Stops the playback of the advertising video.

void stopAdVideo();

Interface InstreamAdPlayer.AdPlayerListener

Methods of the callback interface for the installed AdPlayerListener listener must be invoked by the player in response to the calls of interface methods InstreamAdPlayer upon the occurrence of certain events.

void onAdVideoStarted();

Method should be invoked after a successful start of playback of the advertising video as a response to the call playAdVideo().

void onAdVideoPaused();

Method should be called after pausing ad video playback as a response to the pauseAdVideo () method call.

void onAdVideoResumed();

Method should be invoked after the resumption of the playback of the advertising video as a response to the call resumeAdVideo().

void onAdVideoStopped();

Method should be called after the ad video playback stops, as a response to the stopAdVideo () method call.

void onAdVideoError(String message);

Method should be invoked upon the occurrence of any error during the playback of the advertising video.

void onAdVideoCompleted();

The method must be called when the ad video is finished playing.

void onVolumeChanged(float volume);
The method must be called when the volume changes.

Using the SDK player

myTarget SDK provides a ready-made player for playing ads. To use the SDK player, simply call the useDefaultPlayer() method on the InstreamAd instance you created and add the player to the application screen.

private InstreamAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
     
    // Install the player SDK
    ad.useDefaultPlayer();
    // Add player to the screen
    layout.addView(ad.getPlayer().getView());
}

Download ads

To receive notifications (such as a successful data download or a download error, an ad serving), you must create an InstreamAdListener instance and set it as an event listener, and then you can start the data download.

private InstreamAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
     
    // Set the event listener
    ad.setListener(new InstreamAd.InstreamAdListener()
    {
        @Override
        public void onLoad(InstreamAd instreamAd)
        {
            // The data was successfully loaded
        }
 
        @Override
        public void onNoAd(String reason, InstreamAd instreamAd)
        {
            // No data received
        }
 
        @Override
        public void onError(String reason, InstreamAd ad)
        {
            // An error occurred while playing the promotional video
        }
 
        @Override
        public void onBannerStart(InstreamAd ad, InstreamAd.InstreamAdBanner instreamAdBanner)
        {
            // Ad video playback is started
        }
 
 
        @Override
        public void onBannerPause(InstreamAd ad, InstreamAd.InstreamAdBanner instreamAdBanner)
        {
            // Ad video playback is suspended
        }
 
 
        @Override
        public void onBannerResume(InstreamAd ad, InstreamAd.InstreamAdBanner instreamAdBanner)
        {
            // Ad video playback is resumed
        }
 
        @Override
        public void onBannerComplete(InstreamAd ad, InstreamAd.InstreamAdBanner instreamAdBanner)
        {
            // Ad video playback is finished
        }
 
        @Override
        public void onBannerTimeLeftChange(float timeLeft, float duration, InstreamAd ad)
        {
            // Called repeatedly during the playback of a ad video, it is used to update the timer before the end of the ad video
        }
 
        @Override
        public void onComplete(String section, InstreamAd ad)
        {
            // Playback of all ad videos in the promotional section is complete
        }
 
        @Override
        public void onBannerShouldClose()
        {
            // Called when ad playback should be completed by the developer himself. Example: ad.skip()
        }  
    });
         
    // Start loading data
    ad.load();
}

Display ads

After the data has been successfully uploaded, you can start displaying ad sections. Each partition section can contain multiple ad video, after the playing of each method will be called onBannerStart in the prescribed listener InstreamAdListener, after playing each video method will be called onBannerComplete.

After the playback of all advertising videos in the running section is completed, the onComplete method will be called - this is what you should use for further actions, it will be called even if an error occurred during playback and the onError method was called.

Display of preroll and postroll sections

To display preroll section must before you start showing the video to invoke a method startPreroll instance InstreamAd.

To show the postroll section is necessary after the end of the video to call the method startPostroll.

// Before starting the main video
ad.startPreroll();
 
// After showing the main video
ad.startPostroll();

Display the midroll section

To display the midroll section at some position in the video, after instreamad is created, you must specify an array of positions at which you plan to display the midroll section. Positions can be set in seconds or as a percentage of the video duration.

After successful data loading, an array of positions for which there are promotional videos will be available. That is, if positions were set for the first and fifth seconds, and advertising videos in the downloaded data are only for the first, then there will be only one first position in the available array.

If the positions were not set by the application, they will be set by the server. If the array of positions after loading is empty, then there is no data to show the midroll section.

private InstreamAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
     
    // Set positions on the first and fifth seconds of the video
    ad.configureMidpoints(videoDuration, new float[]{1f,5f});
    // or percentage, 10% and 50% video
    // ad.configureMidpointsPercents(videoDuration, new float[]{10f,50f});
 
    // Set the event listener
    ad.setListener(new InstreamAd.InstreamAdListener()
    {
        @Override
        public void onLoad(InstreamAd instreamAd)
        {
            // The data was successfully loaded
            // Array of positions (in seconds) available to display the midroll section
            adPositions = ad.getMidPoints();
        }
         
        ...
    });
     
    // Start loading data
    ad.load();
}
When the main video reaches one of the positions for the midroll section, it is necessary to call the startMidroll method and pass this position as a parameter to it.

// The video was played to the 5th second and it has a position in the array adPositions
ad.startMidroll(adPositions[1]);

Available ad video properties

An instance of InstreamAdBanner is sent to the onBannerStart and onBannerComplete methods of the InstreamAdListener listener, which contains information about the current advertising video that can be used by the application.

public final float duration;
The duration of the current ad video in seconds.

public final boolean allowClose;
Is it allowed to close the advertising video during playback. Used to control the display of the "Close" or "Skip" button.

public final float allowCloseDelay;

The time in seconds after which the ad video can be closed. Used to control the display of the "Close" or "Skip" button.

public final int videoWidth;
public final int videoHeight;
The width and height of the promotional video.

public String ctaText;

Text for call-to-action button.

public boolean hasAdChoices;
Availability of AdChoices.

public String advertisingLabel;
Advertising headline.

public ImageData adChoicesIcon;
AdChoice icon.

Click processing

The application should independently track clicks on the advertising video (usually on the cta button) and call the handleClick method on InstreamAd instance to process the click and go to the advertised site or application.

private void onAdClick()
{
    ad.handleClick();
}

Condition management

The following control methods are available on the InstreamAd instance.

public void pause()
Pauses the ad video playback.

public void resume()

Resumes advertising video playback.

public void stop()

Stops the advertising section.

public void skip()
Stops the advertising section display if it was done by the user (clicking on the "Skip" or "Close" button).

public void skipBanner()
Stops the current ad video and proceeds to the next if it was done by the user (clicking on the "Skip" or "Close" button).

public void setVolume(float volume)
Sets the volume from 0 to 1.

public void setLoadingTimeout(int loadingTimeout)
Sets the timeout for advertising loading in seconds. In case if after the expiration of the specified interval it was not possible to get banners, the onNoAd callback will be called. The default is 10 seconds, the minimum is 5 seconds.

User Data

For a better selection of advertisements, you can additionally specify the gender and age of the user. If your application uses its own localization model, you can also specify the language of the selected localization in ISO 639-1 format ("ru", "en", "fr", etc.).

To set user data, you need to use the customParams property.

private InstreamAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAd
    ad = new InstreamAd(YOUR_SLOT_ID, this);
    // We receive an instance of additional parameters CustomParams
    CustomParams customParams = ad.getCustomParams();
    // Set age
    customParams.setAge(25);
    // Set gender
    customParams.setGender(CustomParams.Gender.MALE);
}

Samples

Integration examples are available in our demo application on Github.

In-stream audio

myTarget SDK provides the ability to play in-stream audio ads in your application while listening to audio.

Advertising can be launched before the start of audio playback (preroll), during playback (midroll) and after playback (postroll). The SDK downloads data and provides the application with the ability to play ads in the application player.

Initialization

To play advertising audio in your application, you must create an instance of the class InstreamAudioAd. To create an InstreamAudioAd instance, you must specify your slotId.

For each audio in the application, you need to create your own copy of the class InstreamAudioAd.

private InstreamAudioAd ad;
 
private void initAd()
{
    // Enable debug mode
    // MyTargetManager.setDebugMode(true); 
    // Create an instance of InstreamAudioAd
    ad = new InstreamAudioAd(YOUR_SLOT_ID, this);
}

Using the application player

To play ads in the application player, it must implement the InstreamAudioAdPlayer interface and notify the AdPlayerListener listener installed to it.

To use your player, you must call the setPlayer method (InstreamAudioAdPlayer player) on the created instance InstreamAudioAd.

private InstreamAudioAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAudioAd
    ad = new InstreamAudioAd(YOUR_SLOT_ID, this);
     
    // Install the player
    ad.setPlayer(YOUR_PLAYER);
}

Interface InstreamAudioAdPlayer

Interface methods InstreamAudioAdPlayer are called by an instance of InstreamAudioAd. Call them yourself is not required.

float getAdAudioDuration();

Duration of ad audio

float getAdAudioPosition();
Current advertising audio position. The method is called repeatedly during the playback of advertising audio and should give the current value in seconds.

void setAdPlayerListener(AdPlayerListener listener);
Sets the player listener

Context getCurrentContext();

Current context

void setVolume(float volume);

Sets the volume from 0 to 1.

void playAdAudio(Uri uri);

Starts playing ad audio.

uri - the path to audio

void pauseAdAudio();
Pauses the playback of ad audio.

void resumeAdAudio();

Resumes playing advertising audio.

void stopAdAudio();
Stops playing ad audio.

Interface InstreamAudioAdPlayer.AdPlayerListener

The callback methods of the AdPlayerListener interface for the installed listener should be called by the player in response to calls to the methods of the InstreamAudioAdPlayer interface when certain events occur.

void onAdAudioStarted();
The method should be called after the successful start of playing advertising audio, as an answer to the call to the playAdAudio () method.

void onAdAudioPaused();

The method should be called after pausing playback of the ad video, as an answer to the pauseAdVideo() method call.

void onAdAudioResumed();
The method should be called after resuming playback of the advertising audio, as an answer to the call to the resumeAdAudio() method.

void onAdAudioStopped();

The method should be called after stopping the playback of advertising audio, as an answer to the stopAdAudio() method call.

void onAdAudioError(String message);

The method must be called when any error occurs when playing advertising audio.

void onAdAudioCompleted();

The method must be called when the ad audio has been played.

void onVolumeChanged(float volume);

The method must be called when the volume is changed.

Ad downloads

To receive notifications (such as successful data download or download error), you need to create an instance of InstreamAudioAdListener and set it as an event listener, after which you can start downloading data.

private InstreamAudioAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAudioAd
    ad = new InstreamAudioAd(YOUR_SLOT_ID, this);
     
    // Install the event listener
    ad.setListener(new InstreamAudioAd.InstreamAudioAdListener()
    {
        @Override
        public void onLoad(InstreamAudioAd ad)
        {
            // Data uploaded successfully
        }
 
        @Override
        public void onNoAd(String reason, InstreamAudioAd ad)
        {
            // Data not received
        }
 
        @Override
        public void onError(String reason, InstreamAudioAd ad)
        {
            // An error occurred while playing the ad audio
        }
 
        @Override
        public void onBannerStart(InstreamAudioAd ad, InstreamAudioAd.InstreamAudioAdBanner banner)
        {
            // Ad Audio Playback Started
        }
 
        @Override
        public void onBannerComplete(InstreamAudioAd ad, InstreamAudioAd.InstreamAudioAdBanner banner)
        {
            // Ad Audio Playback Completed
        }
 
        @Override
        public void onBannerTimeLeftChange(float timeLeft, float duration, InstreamAudioAd ad)
        {
            // Called repeatedly during the playback of advertising audio, used to update the timer until the end of the display of advertising audio
        }
 
        @Override
        public void onComplete(String section, InstreamAudioAd ad)
        {
            // Playback of all advertising audio in the advertising section is completed.
        }
    });
         
    // We start data loading
    ad.load();
}

Playing ads

After a successful data download, you can start playing ad sections.

Each section of the section can contain several promotional audio, after the start of each playback, the onBannerStart method will be called in the installed InstreamAudioAdListener, after the completion of each audio playback, the onBannerComplete method will be called.

After completion of playback of all advertising audio in the running section, the onComplete method will be called - that's what you should use for further actions. It will be called even if an error occurred during the playback and the onError method was called.

Showing preroll and postroll sections

To play the preroll section, you must call the startPreroll method on the InstreamAudioAd instance before playing the audio.

To play the postroll section, you must call the startPostroll method after the end of the audio playback.

// Before you start playing the main audio
ad.startPreroll();
 
// After playing the main audio
ad.startPostroll();

Show midroll section

To play the midroll section in some audio position, it is necessary after creating an instance of InstreamAudioAd to specify an array of positions where the midroll section will be played. Positions can be set both in seconds and as a percentage of the duration of the audio.

After successful data loading, an array of positions will be available for which there are promotional audio. That is, if positions were set at the first and fifth seconds, and the advertising audio in the downloaded data is only for the first, then there will be only one first position in the available array. If the positions were not specified by the application, they will be set by the server.

If the array of positions after the loading is empty, then there is no data for playing the midroll section.

private InstreamAudioAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAudioAd
    ad = new InstreamAudioAd(YOUR_SLOT_ID, this);
     
    // Set the position in the first and fifth seconds of audio
    ad.configureMidpoints(videoDuration, new float[]{1f,5f});
    // or as a percentage, at 10% and 50% audio
    // ad.configureMidpointsPercents(audioDuration, new float[]{10f,50f});
 
    // Install the event listener
    ad.setListener(new InstreamAudioAd.InstreamAudioAdListener()
    {
        @Override
        public void onLoad(InstreamAudioAd ad)
        {
            // Data uploaded successfully
            // Array of positions (in seconds) available for playing midroll section
            adPositions = ad.getMidPoints();
        }
         
        ...
    });
     
    // We start data loading
    ad.load();
}
When the main audio reaches one of the positions for the midroll section, you must call the startMidroll method and pass this position as a parameter.

// Audio played out to the 5th second and for it there is a position in the adPositions array
ad.startMidroll(adPositions[1]);

Available advertising audio properties

An instance of InstreamAudioAdBanner is sent to the onBannerStart and onBannerComplete methods of the InstreamAudioAdListener listener, which contains information about the current advertising audio that can be used by the application.

float getDuration();

The duration of the current ad audio in seconds.

boolean isAllowSeek();
Is it allowed to scroll through audio advertising.

boolean isAllowSkip();

Is it allowed to skip ad audio.

boolean isAllowTrackChange();

Is it allowed to move to the next track.

List<InstreamAdCompanionBanner> getInstreamAdCompanionBanners();

List of companion banners.

String getAdText();

Promotional text.

Companion banners

The application should independently monitor impressions and clicks on companion banners and call the handleCompanionShow and handleCompanionClick methods in the InstreamAudioAd instance to handle the display and click and go to the advertised site or application.

private void onCompanionAdShow(InstreamAdCompanionBanner companionBanner)
{
    ad.handleCompanionShow(companionBanner);
}
 
private void onCompanionAdClick(InstreamAdCompanionBanner companionBanner)
{
    // Processing a click in the context of current activity
    ad.handleCompanionClick(companionBanner, context);
 
    // Processing a click in the context that was passed during the creation of the advertising instance
    // ad.handleCompanionClick(companionBanner);
}

Condition management

The following management methods are available on the InstreamAudioAd instance.

public void pause()

Pauses the playback of ad audio.

public void resume()

Resumes playing advertising audio.

public void stop()

Stops the advertising section.

public void skip()
Stops the advertising section display if it was done by the user (clicking on the "Skip" or "Close" button).

public void skipBanner()
Stops the current ad audio and proceeds to the next if it was done by the user (clicking on the "Skip" or "Close" button).

public void setVolume(float volume)
Sets the volume from 0 to 1.

public void setLoadingTimeout(int loadingTimeout)

Sets the timeout for advertising loading in seconds. In case if after the expiration of the specified interval it was not possible to get banners, the onNoAd callback will be called. The default is 10 seconds, the minimum is 5 seconds.

User Data

For a better selection of advertisements, you can additionally specify the gender and age of the user. If your application uses its own localization model, you can also specify the language of the selected localization in ISO 639-1 format ("ru", "en", "fr", etc.).

To set user data, you need to use the customParams property.

private InstreamAudioAd ad;
 
private void initAd()
{
    // Create an instance of InstreamAudioAd
    ad = new InstreamAudioAd(YOUR_SLOT_ID, this);
    // Receive an instance of additional parameters CustomParams
    CustomParams customParams = ad.getCustomParams();
    // Set age
    customParams.setAge(25);
    // Set gender
    customParams.setGender(CustomParams.Gender.MALE);
}

Samples

Integration examples are available in our demo application on Github.

Carousel in native advertising

The uploaded banner, instead of one main image, may contain a set of cards that can be displayed in a carousel. Each card contains its own picture, name, description and button. To show the carousel, instead of using the MediaAdView component for the main image, you should use the PromoCardRecyclerView component. As an adapter, it must be given a class that inherits from the abstract PromoCardAdapter class provided by the SDK and implements the getPromoCardView() abstract method. This method must return a visual component for displaying one card that implements the PromoCardView interface. The PromoCardRecyclerView component automatically populates the visual component provided by the adapter with card data. Below is an example of a carousel implementation using PromoCardRecyclerView.

@Override
public void onLoad(NativeAd ad)
{
    NativePromoBanner banner = ad.getBanner();
      
    // ...
    // ...
      
    // List of cards
    List<NativePromoCard> cards = banner.getCards();
   
    // An example of filling a visual component
   
    // ...
    // ...
   
    if (cards.isEmpty())
    {
        // Creating MediaAdView
        MediaAdView mediaView = NativeViewsFactory.getMediaAdView(context);
        adViewLayout.addView(mediaView);
    }
    else
    {
        // Creating PromoCardRecyclerView
        PromoCardRecyclerView promoCardRecyclerView = NativeViewsFactory.getPromoCardRecyclerView(context);
   
        // Installing the adapter
        promoCardRecyclerView.setPromoCardAdapter(new PromoCardRecyclerView.PromoCardAdapter(cards)
        {
             @Override
             public PromoCardView getPromoCardView()
            {
                 return new CardView(context);
            }
        });
          
        adViewLayout.addView(promoCardRecyclerView);  
    }
      
    // Registering a visual component
    ad.registerView(adViewLayout);
   
    // Adding to the screen
    mainLayout.addView(adViewLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
  
// Example class for displaying one card
private static class CardView extends LinearLayout implements PromoCardView
{
   private MediaAdView mediaAdView;
   private TextView titleTextView;
   private TextView descriptionTextView;
   private Button ctaButton;
  
   public CardView(Context context)
   {
      super(context);
      mediaAdView = NativeViewsFactory.getMediaAdView(context);
      titleTextView = new TextView(context);
      descriptionTextView = new TextView(context);
      ctaButton = new Button(context);
      addView(mediaAdView);
      addView(titleTextView);
      addView(descriptionTextView);
      addView(ctaButton);
   }
  
   @Override
   public MediaAdView getMediaAdView()
   {
      return mediaAdView;
   }
  
   @Override
   public TextView getTitleTextView()
   {
      return titleTextView;
   }
  
   @Override
   public TextView getDescriptionTextView()
   {
      return descriptionTextView;
   }
  
   @Override
   public Button getCtaButton()
   {
      return ctaButton;
   }
  
   @Override
   public View getView()
   {
      return this;
   }
}
Carousel
Was this article helpful?