NextGen SDK | Android Integration
Integration Guide for Publishers with Smaato as a Primary Ad Server
(Android NextGen SDK version 21.5.7)
Integrate the NextGen SDK
Set up your account on SPX
Configure your Android project
Add the following repository setup to your project’s main build.gradle file:
allprojects {
repositories {
google()
jcenter()
maven {
url "https://s3.amazonaws.com/smaato-sdk-releases/"
}
}
}
Set the compile options to Java 8, (i.e. place the following line into your application module build.gradle file):
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Add dependencies to your application module build.gradle file.
For all Ad Types, make sure the following dependency is in place:
implementation 'com.smaato.android.sdk:smaato-sdk:21.5.7'
For Banner ads, make sure the following dependencies are in place:
implementation 'com.smaato.android.sdk:smaato-sdk-banner:21.5.7'
For Interstitial ads, make sure the following dependencies are in place:
implementation 'com.smaato.android.sdk:smaato-sdk-interstitial:21.5.7'
For Rewarded ads, make sure the following dependencies are in place:
implementation 'com.smaato.android.sdk:smaato-sdk-rewarded-ads:21.5.7'
For Native ads, make sure the following dependencies are in place:
implementation 'com.smaato.android.sdk:smaato-sdk-native:21.5.7'
Add the following permissions to your application AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
If your application targets Android 5.0 (API level 21) or higher, then you need to add the following line to your application AndroidManifest.xml file:
<uses-feature android:name="android.hardware.location.network" />
If your application targets Android 9 Pie (API level 28) or higher, in order to send HTTP requests (so that more Ads can be shown), then you need to configure the networkSecurityConfig attribute in the application tag in AndroidManifest.xml:
android:networkSecurityConfig="@xml/network_security_config"
Now create the network_security_config.xml in the XML resource directory with:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
For more details regarding the Network security configuration, please see the official Google documentation: https://developer.android.com/training/articles/security-config
Proguard Configuration
If you’re using Proguard in your project, please add the following lines to your Proguard config file, as per your requirements:
-keep public class com.smaato.sdk.** { *; }
-keep public interface com.smaato.sdk.** { *; }
Initialize the NextGen SDK
Add the following to your YourApplication.OnCreate() method, to initialize the Smaato SDK. Additionally, it is recommended to configure the SDK with user information. This is an optional step and can be implemented at a later time.
import android.app.Application;
import com.smaato.sdk.core.AdContentRating;
import com.smaato.sdk.core.Config;
import com.smaato.sdk.core.Gender;
import com.smaato.sdk.core.SmaatoSdk;
import com.smaato.sdk.core.log.LogLevel;
public class YourApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// // initialize SDK first!
Config config = Config.builder()
// log errors only
.setLogLevel(LogLevel.ERROR)
// allow HTTPS traffic only
.setHttpsOnly(true)
.build();
// initialize the Smaato SDK
SmaatoSdk.init(this, config, "SMAATO_PUBLISHER_ID");
// You can also initialize the Smaato SDK without configuration:
// SmaatoSdk.init(this, "SMAATO_PUBLISHER_ID");
// optional configuration
SmaatoSdk.setSearchQuery("bitcoin, lamborghini, san-francisco");
SmaatoSdk.setGender(Gender.MALE); // usually set after user logs in
SmaatoSdk.setAge(40); // usually set after user logs in
// allow the Smaato SDK to automatically get the user's location
SmaatoSdk.setGPSEnabled(true);
}
}
Important Note: Starting from NextGen SDK version 21.2.1, the new GPSEnabled flag allows the SDK to automatically get the user’s location when permission is given by the user. By default, this flag is set to off and the user location will not be provided in the ad request. To enable this the GPSEnabled flag must be set to yes.
Important Details About GDPR
The General Data Protection Regulation (GDPR) was created to provide European users with greater transparency and control over their personal information. As a publisher, you should integrate a Consent Management Platform (CMP) and request for user, vendor, and purpose consents as outlined in IAB Europe’s IAB Tech Lab – CMP API v2. You can find an example implementation of a web-based CMP and the corresponding native wrappers here in the IAB’s GDPR-Transparency-and-Consent-Framework.
You can also make your own custom CMP. The collected end-user consent information needs to be stored in SharedPreferences using the following keys:
Transparency and Consent Framework v2:
Key | Type | Description |
---|---|---|
IABTCF_gdprApplies | Number |
1 = Subject to GDPR |
IABTCF_TCString | String |
Base64-encoded consent string as defined in IAB Tech Lab – Consent string and vendor list formats v2 |
Sample of GDPR Saving in SharedPreferences
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
...
// User is not subject to GDPR
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context_here);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("IABTCF_gdprApplies", 0);
editor.commit();
// Use this example above to set values for the rest of the GDPR keys
Important Details About CCPA
The California Consumer Privacy Act (CCPA) was created to provide California consumers with greater transparency and control over their personal information.
For more information about the CCPA regulation, please check out the Smaato FAQ. You can also review the IAB’s U.S. Privacy String documentation.
For Publishers with California-Based Users
As a publisher, you need to make sure to request consent from California-based users (to give or refuse consent / to opt-out or opt-in ) about private data transfer. This answer should be saved in SharedPreferences with key “IABUSPrivacy_String” in the US Privacy String format (CCPA Opt-Out Storage Format).
The Smaato NextGen SDK reads this value in the key “IABUSPrivacy_String” if it exists and uses this as an optional parameter for all ad requests.
Sample of CCPA Saving in SharedPreferences
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
...
// save the user's consent
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context_here);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("IABUSPrivacy_String", "1YNN"); // for example "1YNN"
editor.commit();
Further Examples of the U.S. Privacy String 1YNN: User has not made a choice to opt-out 1NYY: User has made a choice to opt-out 1—: A Digital Property has determined to use a U.S. Privacy string version 1 and that CCPA does not apply to the transaction.
Ads for Testing Purposes
Adspace ID | Type | Description |
---|---|---|
130626424 | Rich Media | Banner / Med-rect / Leaderboard / Skyscraper |
130635694 | Static Image | Banner / Med-rect / Leaderboard / Skyscraper |
130635706 | MRAID | Banner / Med-rect / Leaderboard / Skyscraper |
130626426 | Rich Media / Video | Interstitial (Video with an end-card + Rich Media Interstitial for 320×480, 480×320, 1024×768 & 768×1024) |
130626427 | Video | Skippable Video |
130626428 | Rewarded | Rewarded Video |
130635048 | Rewarded | Rewarded Video without an end-card |
130783664 | Native | Native with static image main creative |
Showing Banner Ads
Add BannerView to your layout XML:
<com.smaato.sdk.banner.widget.BannerView
android:id="@+id/bannerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In Activity/Fragment, that uses the above layout, get the BannerView, and call loadAd() with your adspaceId and desired bannerAdSize in order to start loading the banner. Optionally, you can also set BannerView.EventListener to listen to events describing the ad’s lifecycle. When your UI component (that hosts the BannerView) is being destroyed, BannerView.destroy() should be called in order to properly release BannerView resources.
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.smaato.sdk.banner.ad.BannerAdSize;
import com.smaato.sdk.banner.widget.BannerView;
public class YourActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find bannerView you setup in your activity.xml
BannerView bannerView = (BannerView) findViewById(R.id.bannerView);
// load banner with desired size
bannerView.loadAd("SMAATO_ADSPACE_ID", BannerAdSize.XX_LARGE_320x50);
}
// You can also set BannerView.EventListener to listen to events describing the advertisement lifecycle:
bannerView.setEventListener(new BannerView.EventListener() {
@Override
// banner ad successfully loaded
public void onAdLoaded(@NonNull BannerView bannerView) {}
@Override
// banner ad failed to load
public void onAdFailedToLoad(@NonNull BannerView bannerView, @NonNull BannerError bannerError) {}
@Override
// banner ad was seen by the user
public void onAdImpression(@NonNull BannerView bannerView) {}
@Override
// banner ad was clicked by the user
public void onAdClicked(@NonNull BannerView bannerView) {}
@Override
// banner ad Time to Live expired
public void onAdTTLExpired(@NonNull BannerView bannerView) {}
});
/* If your UI component (that hosts the BannerView) is being destroyed,
BannerView.destroy() should be called in order to properly release BannerView resources: */
@Override
public void onDestroy() {
super.onDestroy();
bannerView.destroy();
}
}
Showing Interstitial Ads
Call Interstitial.loadAd() with your adspaceId and eventListener in order to start loading the interstitial. This passed eventListener will be used to deliver events describing the ad’s lifecycle. Optionally, you can change the background color for an InterstitialAd. The default is black. Lastly, when the ad is loaded and available for presentation, call showAd(activity) on a received InterstitialAd object to show it to the user.
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.smaato.sdk.interstitial.Interstitial;
import com.smaato.sdk.interstitial.InterstitialAd;
import com.smaato.sdk.interstitial.InterstitialError;
import com.smaato.sdk.interstitial.InterstitialRequestError;
import com.smaato.sdk.interstitial.EventListener;
public class YourActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load interstitial ad
Interstitial.loadAd("SMAATO_ADSPACE_ID", eventListener);
}
EventListener eventListener = new EventListener() {
@Override
//show interstitial ad when it loaded successfully
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
interstitialAd.setBackgroundColor(0xff123456);
interstitialAd.showAd(YOUR_ACTIVITY_HERE);
}
@Override
// interstitial ad failed to load
public void onAdFailedToLoad(@NonNull InterstitialRequestError interstitialRequestError) {}
@Override
// interstitial ad had an unexpected error
public void onAdError(@NonNull InterstitialAd interstitialAd, @NonNull InterstitialError interstitialError) {}
@Override
// interstitial ad opened and was shown successfully
public void onAdOpened(@NonNull InterstitialAd interstitialAd) {}
@Override
// interstitial ad was closed by the user
public void onAdClosed(@NonNull InterstitialAd interstitialAd) {}
@Override
// interstitial ad was clicked by the user
public void onAdClicked(@NonNull InterstitialAd interstitialAd) {}
@Override
// interstitial ad was viewed by the user
public void onAdImpression(@NonNull InterstitialAd interstitialAd) {}
@Override
// interstitial ad Time to Live expired
public void onAdTTLExpired(@NonNull InterstitialAd interstitialAd) {}
};
}
interstitialAd.showAd(activity);
you can change the transparency by setting
interstitialAd.setBackgroundColor(0xaa123456);
and, by using a color with a value different from 0xff as alpha value the InterstitialAd will be shown with a semi-transparent background making the background content of the app partially visible. The value can be from 0-1, where 0 is completely transparent (clear) while 1 is completely opaque (black).
Showing Splash Ads
Splash ads are a special type of full screen interstitial that are shown immediately upon app launch, or on the screen immediately after the launch (splash) screen of a given mobile app. By default, they appear for no longer than 6 seconds and are closable (display) or skippable (video) after 3 seconds. Showing them is similar to showing a standard interstitial.
Create an Activity that inherits from SmaatoSplashActivity and implements the methods getAdSpaceId and getNextActivity. You can utilize the same EventListener as standard interstitials to listen for event callbacks:
public class SplashAdActivity extends SmaatoSplashActivity {
class MyEventListener extends EventListener {
...
}
@NonNull
@Override
protected String getAdSpaceId() {
return "130626426";
}
@NonNull
@Override
protected Class extends Activity> getNextActivity() {
return MainActivity.class;
}
@Override
protected EventListener getEventListener() {
return new MyEventListener();
}
}
a.) If you would like to show your splash ad immediately upon app launch, add the Activity you created to your manifest file:
<activity android:name=".SplashAdActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
b.) If you would like to show your splash ad immediately after your splash screen, you can also start the splash ad after your splash screen:
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
In this case you need to add the Activity you created to your manifest file without the intent filters:
<activity android:name=".SplashAdActivity" />
Showing Rewarded Interstitial Ads
Call RewardedInterstitial.loadAd() with adspaceId and eventListener in order to start loading the rewarded interstitial. As for Interstitial, the eventListener will be used to deliver events describing the ad’s lifecycle. Lastly, when the ad is loaded and available for presentation, call show() on a received RewardedInterstitialAd object to show it to the user.
{@link java.lang.ref.WeakReference}
on eventListener
to prevent memory leaks. It is the responsibility of Soma SDK’s user to hold the reference to a passed eventListener
instance in order to keep it from being collected by the garbage collector.import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.smaato.sdk.rewarded.RewardedInterstitial;
import com.smaato.sdk.rewarded.RewardedInterstitialAd;
import com.smaato.sdk.rewarded.RewardedError;
import com.smaato.sdk.rewarded.RewardedRequestError;
import com.smaato.sdk.rewarded.EventListener;
public class YourActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load rewarded ad
RewardedInterstitial.loadAd("SMAATO_ADSPACE_ID", eventListener);
}
EventListener eventListener = new EventListener() {
@Override
//show rewarded ad when it loaded successfully
public void onAdLoaded(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {
rewardedInterstitialAd.showAd();
}
@Override
// rewarded ad failed to load
public void onAdFailedToLoad(@NonNull RewardedRequestError rewardedRequestError) {}
@Override
// rewarded ad had an unexpected error
public void onAdError(@NonNull RewardedInterstitialAd rewardedInterstitialAd, @NonNull RewardedError rewardedError) {}
@Override
// rewarded ad was closed by the user
public void onAdClosed(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {}
@Override
// rewarded ad was clicked by the user
public void onAdClicked(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {}
@Override
// rewarded ad started playing
public void onAdStarted(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {}
@Override
// rewarded ad finished playing and was watched all the way through
public void onAdReward(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {
// rewarded your user here!
}
@Override
// rewarded ad Time to Live expired
public void onAdTTLExpired(@NonNull RewardedInterstitialAd rewardedInterstitialAd) {}
};
}
Steps to Integrate a Native Ad
The main advantage of integrating Native Ads is the ability to fully control the rendering and appearance of ads on-screen. Other types of ads (Banners, Interstitials, and Rewarded Video) are hardcoded and presented on the screen by the NextGen SDK. With Native Ads, you need to supply different UI components to the SDK to perform the final rendering of an ad.
Native ads might be presented (rendered) on the screen in two different ways:
- Manual rendering. It means you might fetch a native ad’s raw data from the NativeAdAssets assets object and render it into your own custom view layout. You are responsible for downloading the ad’s creatives like the main images and icon.
- Auto rendering. You should create a special subclass that conforms to and implements the NativeAdView interface. This interface defines methods that allow the NextGen SDK to look for appropriated UI controls for a given type of native ad asset, and displays it directly into this certain control. The number of adopted controls from the NativeAdView and their sizes/placements do not matter and depend on your UI/UX preferences. The NextGen SDK handles the downloading of ads creatives itself.
Create a custom layout to represent a native ad:
Create your native ad view.
If manual rendering is chosen, you can create your own ad view with respective assets.
If auto rendering is chosen:
import com.smaato.sdk.nativead.NativeAdView;
class SmaatoNativeAdView implements NativeAdView {
private final View binding;
SmaatoNativeAdView(View binding) {
this.binding = binding;
}
@Nullable
@Override
public TextView titleView() {
return binding.findViewById(R.id.title);
}
@Nullable
@Override
public TextView textView() {
return binding.findViewById(R.id.text);
}
@Nullable
@Override
public TextView sponsoredView() {
// Return null if you don't have this kind of view
return null;
}
@Nullable
@Override
public TextView ctaView() {
return binding.findViewById(R.id.cta);
}
@Nullable
@Override
public View iconView() {
return binding.findViewById(R.id.icon);
}
@Nullable
@Override
public View mediaView() {
return binding.findViewById(R.id.media);
}
@Nullable
@Override
public View ratingView() {
return binding.findViewById(R.id.rating);
}
@Nullable
@Override
public View privacyView() {
return binding.findViewById(R.id.privacy);
}
}
Load a native ad on your activity.
Use the NativeAdRequest object to set loading options:
Set your native ad space ID.
shouldReturnUrlsForImageAssets – Indicates whether the icon and main image creatives should be downloaded. If set to False, the NextGen SDK downloads required creatives and provides all of them as Drawable objects. (True by default)
After that, call one of the overloaded methods:
NativeAd.loadAd(@NonNull Lifecycle owner, @NonNull NativeAdRequest request, @NonNull NativeAd.Listener listener)
NativeAd.loadAd(@NonNull LifecycleOwner owner, @NonNull NativeAdRequest request, @NonNull NativeAd.Listener listener)
NativeAd.loadAd(@NonNull View owner, @NonNull NativeAdRequest request, @NonNull NativeAd.Listener listener)
- If you are using Activities to build your UI and your Activity class extends AppCompatActivity from the AndroidX library, then use this as a .
- If your Activity does not extend from AppCompatActivity, then use com.smaato.sdk.sys.Lifecycling.of(this) to create LifecycleOwner.
- If you are using Fragments to build your UI and your Fragment class extends androidx.fragment.app.Fragment from the AndroidX library, then use getViewLifecycleOwner() as a LifecycleOwner.
- You can use any View that contains your native ad view as a LifecycleOwner.
Render your native ads with NativeAdRenderer. Two ways of rendering depending on whether you chose manual or auto rendering are listed below in the onAdLoaded method (choose one):
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import com.smaato.sdk.nativead.NativeAd;
import com.smaato.sdk.nativead.NativeAdAssets;
import com.smaato.sdk.nativead.NativeAdRequest;
import com.smaato.sdk.nativead.NativeAdError;
import com.smaato.sdk.nativead.NativeAdRenderer;
import com.smaato.sdk.nativead.NativeAdView;
class YourActivity extends Activity {
NativeAdRequest request;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
request.builder().adSpaceId("130783664");
request.builder().shouldReturnUrlsForImageAssets(false); // if manually rendering
// if auto-rendering, set above value to true
// load native ad
NativeAd.loadAd(com.smaato.sdk.sys.Lifecycling.of(this), request, listener);
}
NativeAd.Listener listener = new NativeAd.Listener() {
@Override
public void onAdLoaded(@NonNull NativeAd nativeAd, @NonNull NativeAdRenderer renderer) {
// IMPORTANT: IF YOU CHOSE MANUAL RENDERING, EXECUTE THE BELOW CODE:
View adView = View(); // Inflate your ad view or create it programmatically
// Register ad view for impression tracking and user clicks handling
renderer.registerForImpression(adView);
renderer.registerForClicks(adView.findViewById(R.id.cta));
// Explicit rendering of raw assets into views
NativeAdAssets assets = renderer.getAssets();
adView.findViewById(R.id.title).setText(assets.title());
adView.findViewById(R.id.text).setText(assets.text());
adView.findViewById(R.id.cta).setText(assets.cta());
// If you have chosen shouldReturnUrlsForImageAssets(true) it NativeAdRequest,
// then you have care yourself about image creatives downloading and rendering,
// using UrlConnection class or any library for image loading like Picasso or Glide.
if (assets.icon() != null) {
Picasso.load(assets.icon().uri()).into(adView.findViewById(R.id.icon));
}
// If you have chosen shouldReturnUrlsForImageAssets(false) (default),
// then SmaatoSDK will care about loading all creatives and you will
// able to use them like a Drawable objects
if (assets.icon() != null) {
adView.findViewById(R.id.icon).setImageDrawable(assets.icon().drawable());
}
content.addView(adView); // Add adView into your view hierarchy
// IMPORTANT: IF YOU CHOSE AUTO RENDERING, EXECUTE THE BELOW CODE:
View adView = ... // Inflate your ad view or create it programmatically
NativeAdView nativeAdView = new SmaatoNativeAdView(adView); // Create NativeAdView
renderer.renderInView(nativeAdView); // Render your view using SmaatoSDK
// SmaatoSDK will care about loading all creatives and display them in certain views.
// Register ad view for impression tracking and user clicks handling
renderer.registerForImpression(adView);
renderer.registerForClicks(nativeAdView.ctaView());
content.addView(adView); // Add adView into your view hierarchy
}
@Override
public void onAdFailedToLoad(@NonNull NativeAd nativeAd, @NonNull NativeAdError nativeAdError) {
}
@Override
public void onAdImpressed(@NonNull NativeAd nativeAd) {
}
@Override
public void onAdClicked(@NonNull NativeAd nativeAd) {
}
@Override
public void onTtlExpired(@NonNull NativeAd nativeAd) {
}
};
}
Last Modified: February 9, 2021 at 6:27 am
© 2005-2020 Smaato, Inc. All Rights Reserved. Smaato® is a registered trademark of Smaato, Inc.