Get Started with Vungle - Android or Amazon SDK v. 6

Use this article to integrate the Vungle SDK for Android or Amazon. Starting with v.5.3.0 of our Android SDK, Vungle supports Amazon OS 5.4 and above as a platform. The steps for integrating the Amazon SDK are the same as those for Android, but make sure to use your Amazon app ID for an Amazon integration.

In this article:

GDPR: Recommended Implementation

As of May 25th, the General Data Protection Regulation (GDPR) will be enforced in the European Union. To comply with GDPR, developers have two options.

  • Option 1 (recommended): Publisher controls the GDPR consent process at the user level, then communicates the user’s choice to Vungle. To do this, developers can collect the user’s consent using their own mechanism, and then use Vungle APIs to update or query the user’s consent status. Refer to the GDPR Recommended Implementation Instructions section for details.

  • Option 2: Allow Vungle to handle the requirements. Vungle will display a consent dialog before playing an ad for a European user, and will remember the user’s consent or rejection for subsequent ads.

Before You Begin

Release Highlights

  • Fast: Initialization and ad caching performance is up to five times faster than in v5
  • Lightweight: reduced method counds
    • Core SDK: 750 methods
    • Full integration including third-party libraries: ~4000 methods
  • GDPR compliance: Vungle provides two options for obtaining user consent: either Vungle or the Publisher can control this process. New API calls have been added.

Requirements

  • Android 4.0 (Ice Cream Sandwich - API version 14) or later 

Sample App

Step 1. Include the Vungle SDK in Your Project 

The Vungle SDK is available in two ways: as an AAR via Maven, or JAR integration. 

Option 1. AAR Integration

Open the project-level build.gradle, and add maven URL in the all projects section. 

allprojects {
   repositories {
       maven {
           url 'https://jitpack.io'
       }
   }
}

Open the app-level build.gradle file for your app, and add compile dependencies in the dependencies section.

dependencies {
    …
    // Vungle SDK
compile 'com.github.vungle:vungle-android-sdk:6.2.5'
// Optional Google Play Services - Location and Basement
compile 'com.google.android.gms:play-services-basement:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4' … }

If you include the Vungle SDK via Maven, you can skip "Step 2. Import the Vungle SDK."

Option 2. JAR Integration

  1. Download Vungle SDK v. 6 , unzip it, go to the libs folder, copy all the jars and add them to your project libs folder.

    image1.png
  2. Open the project-level build.gradle, and update the repositories section: 

    allprojects {
        repositories {
            jcenter()
       }
    }
  3. Open the app-level build.gradle file for your app, and add other dependencies in the dependencies section.

    dependencies {
        …
        // Vungle SDK
        compile files('libs/vungle-android-sdk-6.2.5.jar')          
        // Required Third-party Dependencies
        compile files('libs/android-job-1.2.0.jar')
        compile files('libs/cat-1.0.5.jar')
        compile files('libs/converter-gson-2.2.0.jar')
        compile files('libs/fetch-1.1.5.jar')
        compile files('libs/gson-2.7.jar')
        compile files('libs/logging-interceptor-3.7.0.jar')
        compile files('libs/okhttp-3.7.0.jar')
        compile files('libs/okio-1.12.0.jar')
        compile files('libs/retrofit-2.2.0.jar')
        compile files('libs/VNG-moat-mobile-app-kit-2.2.0.jar')
        // Google Play Services
        compile 'com.google.android.gms:play-services-gcm:11.0.4'       // Required
        compile 'com.google.android.gms:play-services-basement:11.0.4'  // Optional
        compile 'com.google.android.gms:play-services-location:11.0.4'  // Optional
        … 
    }
    
  4. If you include the Vungle SDK manually, continue to "Step 2. Import the Vungle SDK." 

  5. Update AndroidManifest.xml by adding the following lines to your AndroidManifest.xml and assigning the application item name to your application class name for multidex:
    
    <!--Required Permissions-->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!--Optional Permissions-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:networkSecurityConfig="@xml/network_security_config" >

    <activity android:name=".MainActivity">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>

    <!-- Google Play Services -->
    <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

    <!-- Vungle -->
    <activity
    android:name="com.vungle.warren.ui.VungleActivity"
    android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
    android:launchMode="singleTop"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />

    <!-- android-job -->
    <service
    android:name="com.evernote.android.job.v21.PlatformJobService"
    android:exported="false"
    android:permission="android.permission.BIND_JOB_SERVICE" />
    <service
    android:name="com.evernote.android.job.v14.PlatformAlarmService"
    android:exported="false"
    android:permission="android.permission.BIND_JOB_SERVICE" />
    <service
    android:name="com.evernote.android.job.v14.PlatformAlarmServiceExact"
    android:exported="false" />
    <receiver
    android:name="com.evernote.android.job.v14.PlatformAlarmReceiver"
    android:exported="false" >
    <intent-filter>
    <!-- Keep the filter for legacy intents -->
    <action android:name="com.evernote.android.job.v14.RUN_JOB" />
    <action android:name="net.vrallev.android.job.v14.RUN_JOB" />
    </intent-filter>
    </receiver>
    <receiver
    android:name="com.evernote.android.job.JobBootReceiver"
    android:exported="false" >
    <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
    <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
    </intent-filter>
    </receiver>
    <service
    android:name="com.evernote.android.job.gcm.PlatformGcmService"
    android:enabled="false"
    android:exported="true"
    android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE" >
    <intent-filter>
    <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
    </intent-filter>
    </service>
    <service
    android:name="com.evernote.android.job.JobRescheduleService"
    android:exported="false"
    android:permission="android.permission.BIND_JOB_SERVICE" />

    </application>

Step 2. Import the Vungle SDK

import com.vungle.warren.Vungle;
import com.vungle.warren.AdConfig;        // Custom ad configurations
import com.vungle.warren.InitCallback;    // Initialization callback
import com.vungle.warren.LoadAdCallback;  // Load ad callback
import com.vungle.warren.PlayAdCallback;  // Play ad callback
import com.vungle.warren.VungleNativeAd;  // Flex-Feed ad

Step 3. Initialize the Vungle SDK 

The initialization method takes the following parameters:

  • List of string of Placement Reference IDs used
  • Vungle Application ID
  • Application context
  • InitCallback
    • onSuccess: notifies when SDK has successfully initialized
    • onError: notifies when the initialization has failed
      • throws IllegalArgumentException if InitCallback is null
      • throws VungleException if required arguments are missing or invalid
    • onAutoCacheAdAvailable: notifies when the auto-cached placement has an ad available to play

The onAutoCacheAdAvailablecallback is available as part of the initialization callback because the SDK will continuously attempt to cache an ad for the auto-cached placement whenever an ad is not pre-cached. This includes when the SDK is started for the first time or when the pre-cached ad for the placement has been played. This will remain true until the process dies or the Vungle instance is reclaimed by garbage collection. For all other placements that are not auto-cached placements, loadAd must be explicitly issued as described in “Step 5. Load an Ad.” 

private final List placement_collection = Arrays.asList("PLACEMENT_1", "PLACEMENT_2", "PLACEMENT_3");

Vungle.init(placement_collection, app_id, this.getApplicationContext(), new InitCallback() {
    @Override
    public void onSuccess() {
        // Initialization has succeeded and SDK is ready to load an ad or play one if there
        // is one pre-cached already
    }

    @Override
    public void onError(Throwable throwable) {
        // Initialization error occurred - throwable.getMessage() contains error message
    }

    @Override
    public void onAutoCacheAdAvailable(String placementId) {
        // Callback to notify when an ad becomes available for the auto-cached placement
        //
        // NOTE: This callback works only for the auto-cached placement. Otherwise, please use
        // LoadAdCallback with loadAd API for loading placements.
    }
};
 

You can check whether Vungle SDK is initialized anytime by calling the isInitialized method:

public static boolean isInitialized()

Step 4. Event Listener

Implement LoadAdCallback for ad load events and PlayAdCallback for ad play events now if you want to use generic callback for all events. Otherwise, skip to “Step 5. Load an Ad” to implement inline callbacks. 

// Implement LoadAdCallback
private final LoadAdCallback vungleLoadAdCallback = new LoadAdCallback() {
    @Override
   public void onAdLoad(String placementReferenceId) {
       // Placement reference ID for the placement to load ad assets
   }

    @Override
    public void onError(String placementReferenceId, Throwable throwable) {
        // Placement reference ID for the placement that failed to download ad assets
        // Throwable contains error message
    }
};
 
// Implement PlayAdCallback
private final PlayAdCallback vunglePlayAdCallback = new PlayAdCallback() {
    @Override
    public void onAdStart(String placementReferenceId) {
        // Placement reference ID for the placement to be played
    }

    @Override
    public void onAdEnd (String placementReferenceId, boolean completed, boolean isCTAClicked) {
        // Placement reference ID for the placement that has completed ad experience
        // completed has value of true or false to notify whether video was
        // watched for 80% or more
        // isCTAClkcked has value of true or false to indicate whether download button
        // of an ad has been clicked by the user
    }

    @Override
    public void onError(String placementReferenceId, Throwable throwable) {
        // Placement reference ID for the placement that failed to play an ad
        // Throwable contains error message
    }
};

Step 5. Load an Ad

In Vungle Android SDK v6, a per-load callback is allowed instead of depending on the global VungleAdEventListener from v5. The LoadAdCallback will be notified about the load state for the call to which it was assigned. The v6 SDK only references this callback and does not store it anywhere; it is the responsibility of the caller to ensure that the callback is managed properly. 

public static void loadAd(@NonNull final String id, @Nullable LoadAdCallback callback) 

The SDK manages the ad asset download for the auto-cached placement, so there is no need to invoke this method for the auto-cached placement. For all other placements, the loadAd method must be invoked and completed successfully before the SDK can play an ad for the placement. The onAdLoad callback will be triggered when this happens. 

// Load Ad Implementation
if (Vungle.isInitialized()) {
    Vungle.loadAd("PLACEMENT_ID", new LoadAdCallback() {
        @Override
        public void onAdLoad(String placementReferenceId) { }

        @Override
        public void onError(String placementReferenceId, Throwable throwable) { }
    };
}

Step 6. Check Ad Availability

Use static method canPlayAdmethod to check if there is an ad available to play for the placement before invoking the playAd() method 

public static boolean canPlayAd(@NonNull String id)

Step 7. Play an Ad

To play an ad, invoke the playAd method, with the placement reference ID, optional AdConfig (null if not being used), and a PlayAdCallback event listener, which will be notified of success or errors during ad playback.

public static void playAd(@NonNull final String id, final AdConfig settings, @Nullable final PlayAdCallback listener) 

You should always check ad availability by calling the canPlayAd method before invoking the playAd method. You must also make sure that an additional playAd is not issued before your receive an onAdEnd or an onError callback from the initial playAd call, because the ad will not render properly if playAd is repeatedly called in quick succession. 

if (Vungle.canPlayAd("PLACEMENT_ID")) {
    Vungle.playAd("PLACEMENT_ID", new AdConfig, new PlayAdCallback() {
        @Override
        public void onAdStart(String placementReferenceId) { }

        @Override
        public void onAdEnd(String placementReferenceId, boolean completed, boolean isCTAClicked) { }

        @Override
        public void onError(String placementReferenceId, Throwable throwable) { }
    });
}

Re-initialize SDK when onError

On rare occurrences, resources can become limited, causing the system to deallocate either part of the Vungle SDK, or some of the third-party dependencies our SDK requires. In such cases, LoadAdCallback/ and PlayAdCallback fire an onError() callback with a Throwable object with a code of ‘VungleException.VUNGLE_NOT_INTIALIZED’. This indicates that the Vungle SDK is an inoperable state and must be re-initialized. 

@Override
public void onError(String placementReferenceID, Throwable throwable) { 
    try {
        VungleException ex = (VungleException) throwable;

        if (ex.getExceptionCode() == VungleException.VUNGLE_NOT_INTIALIZED) {
            initializeVungleSDK();
        }
    } catch (ClassCastException cex) {
        Log.d(LOG_TAG, cex.getMessage());
    }
}

Native Flex Ads

Flex-View Ads

Flex-View ads are loaded and played like regular full-screen ads. Simply call the placement reference ID configured with the placement type 'Flex-View' from the dashboard.

Flex-View can be programmatically closed by issuing the closeFlexViewAd method with the Placement Reference ID that is currently playing the Flex-View ad.

public static boolean closeFlexViewAd(@NonNull final String placementReferenceId)

There is another option to automatically close Flex-View ads after displaying for specified time interval; refer to the Ad Configuration Options section. 

Flex-Feed Ads

The Flex-Feed ad format does not require a full screen to display; instead, the Publisher determines the exact dimensions and location of the ad container within their app. These ad containers can be in collection views or table/list views.

Loading a Flex-Feed Ad

The Publisher must load an ad for the Flex-Feed container. Loading a Flex-Feed ad is same as loading a full-screen or interstitial ad; however, the placement must be configured to support Flex-Feed. Contact your Vungle account manager to enable your placements for Flex-Feed.

Displaying a Flex-Feed Ad

Displaying Flex-Feed ads differs from displaying full-screen ads. With Flex-Feed ads, you must first create a container for the ad. This container is a Layout. You can place said RelativeLayout anywhere on the screen. The ad will scale to any size of container, but keep in mind that very low resolution will make ads less visible. You must then call the Vungle.getNativeAd to get the Flex-Feed ad object and call the addView function to associate the container with the Flex-Feed ad.

private RelativeLayout flexfeed_container = findViewById(...);

VungleNativeAd vungleNativeAd = Vungle.getNativeAd("FLEXFEED_ID", vunglePlayAdCallback);
View nativeAdView = vungleNativeAd.renderNativeView();
flexfeed_container.addView(nativeAdView);

Closing a Flex-Feed Ad

Because the Flex-Feed Ad view has been added to your container view, it must also be removed in case the ad view disappears from the screen, the activity or fragment is destroyed, or the parent view container is recycled or destroyed. Without your closing the ad, such an event will cause unexpected behaviour in your app.

private VungleNativeAd vungleNativeAd;

// Calling finishDisplayingAd when you want to finish displaying Flex-Feed Ad will trigger onAdEnd and will tell you when you can remove the child FlexFeed view container
vungleNativeAd.finishDisplayingAd();

// And removing empty ad view from container
@Override 
public void onAdEnd(String id, boolean completed) {
    …
    parentView.remove(nativeAdView);
    vungleNativeAd = null;
    …
}

Attaching and Detaching the State of a Flex-Feed Ad

If the user scrolls to a point where the video ad is no longer visible on the screen, the Publisher must pause the video, and resume it when it is again visible. To control the pause and resume states, call setAdVisibility() from the VungleNativeAd instance, and set it to ‘true’ when the video is visible and to ‘false’ when the video goes off screen. The setAdVisibility is not to be confused with View visibility: this setter informs Vungle SDK whether the Native ad view is visible or not, and depending on it, the SDK pauses/resumes video playback.

To pause a Flex-Feed ad:

vungleNativeAd.setAdVisibility(false);

To resume a Flex-Feed ad:

vungleNativeAd.setAdVisibility(true);

Advanced Settings 

Google Play Services (Optional)

Including Google Play Services with your project allows Vungle to provide a more customized ad experience to the end user. Google Cloud Messaging is required API, while Google Location and Activity Recognition and Google Location and Basement API’s are optional. We recommend using version 11.0.1 or higher. 

To include Google Play Services, we recommend Google's setup guide. In your app, ensure that the device has a sufficiently updated version of Google Play Services. Vungle SDK optionally utilizes the location and ads API from Google Play Services. 

  • google.android.gms:play-services-gcm:11.0.1 // Required
  • google.android.gms:play-services-basement:11.0.1 // Recommended
  • google.android.gms:play-services-location:11.0.1 // Recommended

Method Count Reduction

Adding Vungle Android SDK v6 to your project will add approximately 750 core Vungle methods, excluding any transitive dependencies. A full integration including third-party libraries is expected to add less than 4000 methods in average. Consider the following suggestions to reduce the total number of methods added to your project. 

  • ProGuard: You can enable ProGuard to shrink your project code. It will discard any unused classes at the time of compilation to make the total method count as small as possible. You can enable it by specifying minifyEnabled true in build.gradle for appropriate build type and by providing the rules to keep the classes that is required by your project.

  • Multidex: If you are still above a 65K method count, enabling multiDex may be the only solution provided by Google. You need to configure your project to multiDex only one time, but it will have an impact on build and app startup time. 

Proguard

If you are using Proguard, add the following rules to your ProGuard configuration file:

# Vungle
-keep class com.vungle.warren.** { *; }

# Evernote
-dontwarn com.evernote.android.job.gcm.**
-dontwarn com.evernote.android.job.GcmAvailableHelper

-dontwarn com.google.android.gms.ads.identifier.**

-keep public class com.evernote.android.job.v21.PlatformJobService
-keep public class com.evernote.android.job.v14.PlatformAlarmService
-keep public class com.evernote.android.job.v14.PlatformAlarmReceiver
-keep public class com.evernote.android.job.JobBootReceiver
-keep public class com.evernote.android.job.JobRescheduleService

-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-keep class com.google.android.gms.internal.** { *; }

# Moat SDK
-keep class com.moat.** { *; }
-dontwarn com.moat.**

UI Thread Note

Callbacks are executed on a background thread, so any UI interaction or updates resulting from an event callback must be passed to the main UI thread before executing. Two common ways to run your code on the UI thread are:

Ad Configuration Options

Ad Configuration

You have the option to customize individual ads you play by providing a new adConfig object to playAd. AdConfig is an object and can be null, in which case the ad will play with default configurations; or it can be a non-null with overrides to the AdConfig setter. The following is an example of how to use AdConfig:

Vungle.playAd(placementReferenceID, null, vunglePlayAdCallback);

The above uses null as a the adConfig object; you can do this if you do not want to set any additional configurations. Use an AdConfig object as shown here:

AdConfig adConfig = new AdConfig();
adConfig.setAutoRotate(true);
adConfig.setMuted(true);
Vungle.playAd(placementReferenceID, adConfig, vunglePlayAdCallback);

The following table shows all the available AdConfig options.

Option

Description

setBackButtonImmediatelyEnabled

true if back button should be enabled before ad close button appears, false otherwise

setFlexViewCloseTime

takes an Integer value that is greater or equal to 0 that specifies time in seconds for Flex-View ad to automatically close itself

setImmersiveMode

true if immersive mode will be enabled for KitKat+ devices, false otherwise

setAutoRotate

true if the video ad is supposed to auto-rotate, false to follow video ad orientation

setMuted

true if the video should start with its audio settings matching those of your enclosing application, false if it should start muted regardless

setOrdinal

Takes an Integer value of ordinal count to track the number of ads that has been played in same session

setTransitionAnimationEnabled

true if the video transition animation should be enabled, false if it should be disabled

You may use the same AdConfig object for multiple ads Placement Reference IDs you play.

Additional Rewarded Ad Configuration

You can use the Vungle object to set rewarded video settings.

Option

Description

setIncentivizedFields(@Nullable String userID, @Nullable String title, @Nullable String body, @Nullable String keepWatching, @Nullable String close)

When a user tries to close a Rewarded video, a popup will display to confirm that’s what the user wants to do. You can customize the pop-up with this setting. Use null when you do not want to modify the default value; for example, if you only want to change the userID.

Set Rewarded Ad Configuration as follows:

Vungle.setIncentivizedFields("user1","title1","body1","keepwatching1","close1");
Vungle.playAd("YOUR_APP_ID", AdConfig, vunglePlayAdCallback);

List of Valid Placements

A helper method that returns Collection of String containing all valid Placement Reference IDs for the current session.

public static Collection getValidPlacements()

GDPR Recommended Implementation Instructions

To use Vungle APIs to update or query the user’s consent status (as recommended in Option 1 of Vungle's GDPR: Recommended Implementation), use these functions:


// To set the user's consent status to opted in:
Vungle.updateConsentStatus(Vungle.Consent.OPTED_IN);

// To set the user's consent status to opted out:
Vungle.updateConsentStatus(Vungle.Consent.OPTED_OUT);

// To find out what the user's current consent status is:
Vungle.Consent currentStatus = Vungle.getConsentStatus();

Hardware Acceleration

Hardware acceleration is enabled by default if your target API level is set to 14 or above. This option must be enabled for the SDK to properly show Dynamic Template and Native Flex ads. Please make sure this option is set to 'true' in your project:

<application android:hardwareAccelerated="true" ...>

Additional Notes

Android Studios has a known issue in which you may get the crash shown below. If you have the latest Android Studios Instant Run, disable Android Studios Instant Run to get rid of this crash.

1-20 13:53:03.649 27642-27828/com.publisher.sample W/GooglePlayServicesUtil: Google Play services out of date. Requires 10240000 but found 9879438
11-20 13:53:03.659 27642-27828/com.publisher.sample W/VungleDevice: Google Play Services not available: SERVICE_VERSION_UPDATE_REQUIRED
11-20 13:53:05.679 27642-27642/com.publisher.sample D/Event: No subscribers registered for event class com.vungle.publisher.lu
11-20 13:53:05.679 27642-27642/com.publisher.sample D/Event: No subscribers registered for event class de.greenrobot.event.NoSubscriberEvent
Have more questions? Submit a request

Comments