Get Started with Vungle - Android SDK v. 5

Use this article to integrate the Vungle SDK for Android or Amazon. Starting with v.5.3.2 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.

Contents

Requirements

  • Android 4.0 (Ice Cream Sandwich - API version 14) or later
  • Java 1.7 - For Android 5.+ compatibility purposes, JDK 7 is required
  • Java 1.8 - For Android 7.+ compatibility purposes, JDK 8 is required

Step 1. Include the Vungle SDK in Your Project

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

Option 1. Including the Vungle SDK as an AAR via Maven

Open the project-level build.gradle, and add maven URL in the all project 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 {
    …
    compile 'com.github.vungle:vungle-android-sdk:5.3.2'
compile 'com.google.android.gms:play-services-basement:11.4.0'  //use version 11.0.1 and up only compile 'com.google.android.gms:play-services-location:11.4.0'  //use version 11.0.1 and up only
… }

If you include the Vungle SDK via Maven, you can skip "Step 2. Update AndroidManifest.xml."

Option 2. Downloading the Vungle SDK and Including it in Your App

Download Vungle SDK, unzip it, go to libs folder, copy all the jars and add it to your project library.

Screen_Shot_2017-10-05_at_2.51.15_PM.png

Open the project-level build.gradle, and update the repositories section.

allprojects {
    repositories {
        jcenter()
    }
}

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

android{
...
    packagingOptions{
        exclude 'META-INF/rxjava.properties'
    }
...
}

dependencies {
    …
    compile files('libs/adapter-rxjava-2.2.0.jar')
    compile files('libs/converter-gson-2.2.0.jar')
    compile files('libs/dagger-2.7.jar')
    compile files('libs/eventbus-2.2.1.jar')
    compile files('libs/gson-2.7.jar')
    compile files('libs/javax.inject-1.jar')
    compile files('libs/okhttp-3.6.0.jar')
    compile files('libs/okio-1.11.0.jar')
    compile files('libs/publisher-sdk-android-5.3.2.jar')
    compile files('libs/retrofit-2.2.0.jar')
    compile files('libs/rxjava-1.2.0.jar')

    compile 'com.google.android.gms:play-services-basement:11.4.0'  //use version 11.0.1 and up only
    compile 'com.google.android.gms:play-services-location:11.4.0'  //use version 11.0.1 and up only
    … 
}

If you include the Vungle SDK manually, continue to "Step 2. Update AndroidManifest.xml."

Step 2. Update AndroidManifest.xml

Add the following lines to your AndroidManifest.xml, assigning the application item name to your application class name for multidex:

<!-- Required permissions for caching and ad operations to work -->
<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 to enable better geo-targeting of ads (recommended) -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:name=".(YourApplicationName)"
    ...
<activity android:name="com.vungle.publisher.VideoFullScreenAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>

<activity android:name="com.vungle.publisher.MraidFullScreenAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>

<activity android:name="com.vungle.publisher.FlexViewAdActivity"
android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>
>

Step 3. Initialize the Vungle SDK

Note: A default placement is created for each app automatically. You must provide its placement reference ID in this initialization step whether or not you plan to take advantage of the placements functionality. If you create multiple placements, provide all the reference IDs.

Application Startup

Initialize the Vungle Publisher SDK in your application's first Activity with the active placement reference IDs you want to use inside the app. The SDK will be initialized asynchronously and will return a callback to the VungleInitListener provided in init.

public class FirstActivity extends android.app.Activity {

  // get the VunglePub instance
  final VunglePub vunglePub = VunglePub.getInstance();

  // get your App ID from the app's main page on the Vungle Dashboard after setting up your app
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // initialize Publisher SDK with app id, placement reference id list and init callback handler
      vunglePub.init(this, app_id, new String[] { placementID1, placementID2, placementID3 }, new VungleInitListener() {

            @Override
            public void onSuccess() { }
            @Override
            public void onFailure(Throwable e){ }
        });
    }
}

Each Activity

In addition, override the onPause and onResume methods in each Activity (including the first) to ensure that the Vungle Android SDK is properly updated when your application gains or loses focus. 

public class EachActivity extends android.app.Activity {

  // get the VunglePub instance
  final VunglePub vunglePub = VunglePub.getInstance();
  ...
  @Override
  protected void onPause() {
      super.onPause();
      vunglePub.onPause();
  }

  @Override
  protected void onResume() {
      super.onResume();
      vunglePub.onResume();
  }
}

Step 4. Set the Listeners

The Vungle SDK raises several events that you can handle programmatically by implementing VungleAdEventListener classes and registering them using clearAndSetEventListeners. Remember to remove the eventListener when you don't need to use it anymore to prevent memory leaks.

vunglePub.clearAndSetEventListeners(vungleDefaultListener, vungleSecondListener);

Step 5. Load and Play an Ad

Once the Vungle SDK is successfully initialized, you can load your placement and play the ad when it's ready. If you set the VungleAdEventListener, it will notify through the onAdAvailabilityUpdate(String placementReferenceId, boolean isAdAvailable) callback when an ad is available to play. 

public class GameActivity extends android.app.Activity {

    // get the VunglePub instance
    final VunglePub vunglePub = VunglePub.getInstance();
    final String placementIdForLevel = "your placement reference id";
 
    private void onLevelStart() {() {
        vunglePub.loadAd(placementIdForLevel);
    }

    private void onLevelComplete() {
        if (vunglePub.isAdPlayable(placementIdForLevel)) {
            vunglePub.playAd(placementIdForLevel, globalAdConfig);
        }
    }
}

Note that for the auto-cached placement, you don't need to call loadAd because the SDK will automatically load an ad after initialization. We recommend choosing most viewed placement as your auto-cached selection. 

To define whether a user has the option to close out of an ad, use the forced view options in the Vungle Dashboard.

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, but it's not required. We recommend using version 8.4.0 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-location:11.0.1
  • google.android.gms:play-services-ads:11.0.1
  • For play-services 7.8.0 and below: retain the support library
  • For play-services 8.4.0 and above: support library is not required

We have successfully compiled our standalone SDK for compilation with the following versions of Google Play Services: 7.8.0, 8.4.0, 9.8.0, 10.2.4, 11.0.1.

65K Dalvik Method Limit

Adding Vungle Android SDK 5.1.0 to your project will add 6,557 methods, excluding any other dependencies that are required. We do have plans to reduce the method count in our project pipeline, and this is the current limitation. Consider the following suggestions to reduce the total number of methods added to your project.

  • Selective Gradle Compilation: Google Play Services (GPS) SDK has about 20K method counts. If your project is using GPS, there is an option to selectively compiling GPS SDK that is required by your project.
    • com.google.android.gms:play-services-location:11.0.1
    • com.google.android.gms:play-services-ads:11.0.1

  • 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
-dontwarn com.vungle.**
-dontnote com.vungle.**
-keep class com.vungle.** { *; }
-keep class javax.inject.*

# GreenRobot
-dontwarn de.greenrobot.event.util.**

# RxJava
-dontwarn rx.internal.util.unsafe.**
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   rx.internal.util.atomic.LinkedQueueNode producerNode;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
   rx.internal.util.atomic.LinkedQueueNode consumerNode;
}
-keep class rx.schedulers.Schedulers { public static <methods>; }
-keep class rx.schedulers.ImmediateScheduler { public <methods>; }
-keep class rx.schedulers.TestScheduler { public <methods>; }
-keep class rx.schedulers.Schedulers { public static ** test(); }
# MOAT -dontwarn com.moat.** -keep class com.moat.** { public protected private *; }
# Retrofit -dontwarn okio.** -dontwarn retrofit2.Platform$Java8

The EventListener Interface

Available methods to manipulate the VungleAdEventListener are listed below: 

Method

Description

clearAndSetEventListeners(VungleEventListener..)

Clears registered EventListeners and then adds the input eventListeners.

clearEventListeners( )

Clears all EventListeners

removeEventListeners(VungleEventListener..)

Removes the input EventListeners.

addEventListeners(VungleEventListener..)

Adds the input eventListeners

VungleAdEventListener delegate call API:

public class FirstActivity extends android.app.Activity {
  
  private final VungleAdEventListener vungleListener = new VungleAdEventListener(){

    @Override
    public void onAdEnd(String placementReferenceId, boolean wasSuccessfulView, boolean wasCallToActionClicked) {
      // Called when user exits the ad and control is returned to your application        
      // if wasSuccessfulView is true, the user watched the ad and should be rewarded       
      // (if this was a rewarded ad).
      // if wasCallToActionClicked is true, the user clicked the call to action
      // button in the ad.    
    }

    @Override
    public void onAdStart(String placementReferenceId) {
      // Called before playing an ad
    }

    @Override
    public void onUnableToPlayAd(String placementReferenceId, String reason) {
      // Called after playAd(placementId, adConfig) is unable to play the ad       
    }

    @Override
    public void onAdAvailabilityUpdate(String placementReferenceId, boolean isAdAvailable) {
      // Notifies ad availability for the indicated placement
      // There can be duplicate notifications
    }
  };

  @Override
  public void onDestroy() {
    vunglePub.clearEventListeners();
    super.onDestroy();
  };
}

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:

Configuration Options

Global Ad Configuration

After calling init, you must also set up the global AdConfig object. By default you can use this AdConfig object in each playAd call. This object also allows you to set options that will be automatically applied to every ad you play.

public class FirstActivity extends android.app.Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    vunglePub.init(this, app_id, placement_list, new VungleInitListener() {
      @Override
      public void onSuccess() {
        // get a reference to the global AdConfig object 
        final AdConfig globalAdConfig = vunglePub.getGlobalAdConfig(); 
        // For a full description of available options, see the 'Config Object'section. 
        globalAdConfig.setSoundEnabled(true);
      }
      @Override
      public void onFailure(Throwable e) { }
    });
  } 
}

Single Ad Configuration

You must use an AdConfig object anytime you call playAd. But you have the option to customize individual ads you play by providing a new AdConfig object to playAd. If you set any options in the global ad configuration, those global options will be overridden by the options provided in AdConfig. Pass an override AdConfig as follows:

public class GameActivity extends android.app.Activity {
  …
  private void onLevelComplete() {
    // create a new AdConfig object
    final AdConfig overrideConfig = new AdConfig();

    overrideConfig.setSoundEnabled(false);
 
    // the overrideConfig object will only affect this ad play.
    vunglePub.playAd(yourPlacementId, overrideConfig);
  }
}

The AdConfig Object

The override AdConfig has a collection of options that can be set for an individual ad play.

Note: Rewarded ads are in some cases referred to as incentivized ads; both terms always refer to the same kind of ad. In the SDK code and in our Reporting API, we use the term 'incentivized'.

Available options are listed below:

Method

Default

Description

setOrientation

Orientation.matchVideo

Orientation.autoRotate indicates that the ad will autorotate with the device orientation.

Orientation.matchVideo indicates that that the ad will play in the best orientation for the video (usually landscape).

setSoundEnabled

true

Sets the starting sound state for the ad. If true, the audio respects device volume and sound settings. If false, video begins muted but user may modify.

setBackButtonImmediatelyEnabled

false

If true, allows the user to immediately exit an ad using the back button. If false, the user cannot use the back button to exit the ad until the on-screen close button is shown.

setImmersiveMode

false

Enables or disables immersive mode on KitKat+ devices

setIncentivizedUserId

none

Sets the unique user id to be passed to your application to verify that this user should rewarded for watching an incentivized ad. N/A if ad is not incentivized.

 

setIncentivizedCancelDialogTitle

"Close video?"

Sets the title of the confirmation dialog when skipping an incentivized ad. N/A if ad is not incentivized.

setIncentivizedCancelDialogBodyText

"Closing this video early will prevent you from earning your reward. Are you sure?"

Sets the body of the confirmation dialog when skipping an incentivized ad. N/A if ad is not incentivized.

setIncentivizedCancelDialogCloseButtonText

"Close video"

Sets the 'cancel button' text of the confirmation dialog when skipping an incentivized ad. N/A if ad is not incentivized.

setIncentivizedCancelDialogKeepWatchingButtonText

"Keep watching"

Sets the 'keep watching button' text of the confirmation dialog when skipping an incentivized ad. N/A if ad is not incentivized.

setTransitionAnimationEnabled

false

Enables or disables standard fragment transition animation

 

Have more questions? Submit a request

Comments