Knowledge base

Android integration guide

Overview

This guide covers basic integration for implementing Unity Ads in your native Android game.

  • If you are a Unity developer using C#, click here.
  • If you are an iOS developer using Objective-C, click here.

Unity’s monetization platform provides you with powerful revenue tools. If your game uses in-app purchases as well as ads, Unity’s machine learning data model can seamlessly blend content types for an optimized monetization strategy. To learn more about how Unity helps you optimize revenue, see documentation on Personalized Placements.

In this guide:

Basic implementation

Creating a Project on the Unity Developer Dashboard

If you don't have a Unity Developer (UDN) account yet, create one here. When you have an account, follow these steps to create a Unity Project:

  1. Log in to the Developer Dashboard, and navigate to the Operate tab.
  2. Select Projects from the left navigation bar.
  3. Click the NEW PROJECT button in the top right corner.

Locate your Project’s Game ID by selecting your Project, then selecting Monetization > Platforms from the left navigation bar. Copy the Apple App Store Game ID, as you will need it to activate the Unity Ads service in your game.

Creating a Placement

Placements are triggered events within your game that display monetization content. Manage Placements from the Operate tab of the Developer Dashboard by selecting your Project, then selecting Monetization > Placements from the left navigation bar.

Click the ADD PLACEMENT button to bring up the Placement creation prompt. Name your Placement and select its type:

  • Select Non-rewarded to show basic interstitial ads or promotional content. Non-rewarded Placements allow players to skip the ad after a specified period of time.
  • Select Rewarded to allow players to opt-in to viewing ads in exchange for incentives. Rewarded Placements do not allow the player to skip the ad.
  • Select Banner to create a dedicated Banner ad Placement.

Every Unity Ads-enabled project has a (non-rewarded) ‘video’ and (rewarded) ‘rewardedVideo’ Placement by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

Importing the Unity Ads framework

Download the Unity Ads framework here, specifically unity-ads.aar. The UnityMonetization API requires SDK 3.0 or later.

Using Android Studio

  1. Create or open your existing Android project in Android Studio.
  2. Add a new module and import the unity-ads.aar file. Name the module "unity-ads", for example.
  3. Right-click on the module in the project view, then select Open Module Settings > app, and add "unity-ads" module as a dependency.
  4. Add the following imports to your java Activity file:
import com.unity3d.services.IUnityServicesListener;
import com.unity3d.services.monetization.UnityMonetization;

Without Android Studio

If you can't use the .aar packages with your build system, Unity also provides the same resources in a ZIP file (unity-ads.zip in GitHub releases). Follow these steps to use Unity Ads:

  1. Include classes.jar in your build.
  2. Manually merge the manifest from AndroidManifest.xml. Make sure you include both AdUnitActivity and AdUnitSoftwareActivity activities. You also need to add the INTERNET and ACCESS_NETWORK_STATE permissions.
  3. If you are using ProGuard, add all lines from proguard.txt to your ProGuard configuration.

Initializing the Unity Ads SDK

To initialize the SDK, you must reference your Project’s Game ID for the appropriate platform. You can locate the ID on the Operate tab of the Developer Dashboard by selecting the Project, then selecting Monetization > Platforms from the left navigation bar.

Locating your Game ID in the Developer Dashboard

In your game script, call the initialize method to initialize the SDK early in your game’s run-time life cycle, before you need to show ads. For example:

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_main);

     UnityServices.initialize (myActivity, unityGameID, myListener, true);
}

In this example, the myActivity variable is the current Android Activity. The unityGameID variable is the Game ID for your Project found on the Developer Dashboard. The myListener variable is the listener for IUnityMonetizationListener callbacks. The true boolean indicates that the game is in test mode, and will only show test ads.

Implementing basic (non-rewarded) ads

PlacementContent is an object representing monetization content that your Placement can display (for more information, see documentation on Content types and Personalized Placements). Use the getPlacementContent function to retrieve content when it’s ready to display, and the show function to display it. For example:

@Override
    public void showAds (View view) {

        // Check if the Placement is ready:
        if (UnityMonetization.isReady (placementId)) {
            // Retrieve the PlacementContent that is ready:
            PlacementContent pc = UnityMonetization.getPlacementContent (placementId);
            // Check that the PlacementContent is the desired type:
            if (pc.getType ().equalsIgnoreCase ("SHOW_AD")) {
                // Cast the PlacementContent as the desired type:
                ShowAdPlacementContent p = (ShowAdPlacementContent) pc;
                // Show the PlacementContent:
                p.show (this, this);
            }
        } else {
            Log.e ("This Placement is not ready!");
        }
    }

Implementing rewarded ads

Rewarding players for watching ads increases user engagement, resulting in higher revenue. For example, games may reward players with in-game currency, consumables, additional lives, or experience-multipliers. For more information on how to effectively design your rewarded ads, see documentation on Ads best practices.

To reward players for watching ads, follow the same steps as detailed in the basic implementation section, but show the ad using a reward callback method with custom logic for players completing the ad.

Selecting a Placement

You must display rewarded ads through Rewarded Placements. Every Unity Ads-enabled Project also has a ‘rewardedVideo’ Placement by default. Feel free to use this for your implementation, or create your own (but make sure your Placement is configured as Rewarded).

Adding a callback method to your script

The show function takes an onAdsFinished callback method that the SDK uses to return a FinishState enum. This result indicates whether the player finished or skipped the ad. Use this information to write a custom function for how to handle each scenario. For example:

@Override
public void onAdFinished (String s, UnityAds.FinishState finishState) {
    if (finishState == UnityAds.FinishState.COMPLETED) {
        if (s.equals (rewardedPlacementId)) {
            // Reward the player here.
        }
    }
}

Rewarded ads button code example

The following example checks at a specific point in the game whether PlacementContent is ready to display. As an alternate method, you can implement a listener to notify you when content is available.

public class MainActivity extends AppCompatActivity implements View.OnClickListener, IUnityServicesListener, IShowAdListener {
    private Button rewardedAdsButton;
    private String unityGameID = "1234567";
    private String interstitialPlacementId = "video";
    private String rewardedPlacementId = "rewardedVideo";

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);

        UnityServices.initialize (this, unityGameID, this);

        rewardedAdsButton = findViewById (R.id.rewardedAdsButton);
        rewardedAdsButton.setOnClickListener (this);
    }

    @Override
    public void onClick (View view) {
        if (UnityMonetization.isReady (rewardedPlacementId)) {
            PlacementContent pc = UnityMonetization.getPlacementContent (rewardedPlacementId);
            if (placement.getType ().equalsIgnoreCase ("SHOW_AD")) {
                ShowAdPlacementContent p = (ShowAdPlacementContent) pc;
                p.show(this, this);
            }
        } else {
            Log.e ("This Placement is not ready!");
        }
    }

    @Override
    public void onAdFinished (String s, UnityAds.FinishState finishState) {
        if (finishState == UnityAds.FinishState.COMPLETED) {
            if (s.equals (rewardedPlacementId)) {
                // Reward the player here.
            }
        }
    }
}

Implementing Banner ads

Placement configuration

Banner ads require a specific type of dedicated banner Placement. Banners currently display anchored on the bottom-center of the screen.

Example of a banner ad in-game

Script implementation

In your game script, import the UnityBanners API, then implement an IUnityBannerListener class to provide callbacks to the SDK. Use the loadBanner and destroy functions to show or hide the banner. The following script sample is an example implementation for displaying banner ads.

public class UnityBannerExample extends Activity {
    private View bannerView;
    private Button bannerButton;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.unityads_example_layout);
        final Activity myActivity = this;

        final IUnityBannerListener unityBannerListener = new UnityBannerListener ();
        final IUnityMonetizationListener unityMonetizationListener = new UnityMonetizationListener ();

        UnityBanners.setBannerListener (unityBannerListener);

        bannerButton = (Button) findViewById (R.id.unityads_example_banner_button);
        bannerButton.setEnabled (true);
        bannerButton.setOnClickListener (new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                if (bannerView == null) {
                    UnityBanners.loadBanner (myActivity, "banner");
                } else {
                    UnityBanners.destroy ();
                }
            }
        });

        final Button initializeButton = (Button) findViewById (R.id.unityads_example_initialize_button);
        initializeButton.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
            }
        });
    }

    private class UnityBannerListener implements IUnityBannerListener {

        @Override
        public void onUnityBannerLoaded (String placementId, View view) {
            bannerView = view;
            ((ViewGroup) findViewById (R.id.unityads_example_layout_root)).addView (view);
        }

        @Override
        public void onUnityBannerUnloaded (String placementId) {
            bannerView = null;
        }

        @Override
        public void onUnityBannerShow (String placementId) {
        }

        @Override
        public void onUnityBannerClick (String placementId) {
        }

        @Override
        public void onUnityBannerHide (String placementId) {
        }

        @Override
        public void onUnityBannerError (String message) {

        }
    }

    private class UnityMonetizationListener implements IUnityMonetizationListener {

        @Override
        public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
        }

        @Override
        public void onPlacementContentStateChange (String placementId, PlacementContent placementContent, UnityMonetization.PlacementContentState previousState, UnityMonetization.PlacementContentState newState) {
        }

        @Override
        public void onUnityServicesError (UnityServices.UnityServicesError error, String message) {
        }
    }
}

Testing

Prior to publishing your game, enable test mode by following these steps:

  1. From the Operate tab of the Developer Dashboard, select your Project.
  2. Select Monetization > Platforms from the left navigation bar.
  3. Select the desired platform, then select the SETTINGS tab.
  4. Scroll down to the TEST MODE section and toggle override client test mode, then select the Force test mode ON radio button.

Run your project and test your ads implementation.

Note: You must enable test mode before testing ads integration, to avoid getting flagged for fraud.

Optimizing your revenue

Congratulations on implementing Unity Ads! Our goal is to make it easy for you to maximize your revenue. With that in mind, consider these next steps:

  • If your game uses in-app purchasing, implement IAP Promo using purchasing integration for Android to promote your in-app offers.
  • When you have Ads and IAP Promo set up, use Personalized Placements to turbocharge your ads and IAP strategy and provide revenue lift for your entire game.
  • Review our Best practices guide for insight on how to design effective ad mechanics.

Back to top

Android API reference

UnityServices

Initialize

Initializes Unity Ads in your game at run time. To avoid errors, initialization should occur early in the game’s run-time lifecycle, preferably at boot. Initialization must occur prior to showing ads.

public static void initialize (final Activity activity, final String gameId, final IUnityMonetizationListener listener, final boolean testMode);

The activity parameter is the current Android Activity. The gameID parameter is the Game ID for your Project found on the Developer Dashboard. The listener parameter is the listener for IUnityMonetizationListener callbacks. The testMode parameter indicates whether the game is in test mode. When testMode is true, you will only see test ads. When testMode is false, you will see live ads. It is important to use test mode prior to launching your game, to avoid being flagged for fraud.

getDebugMode and setDebugMode

Methods for checking or setting whether the game is in test mode.

public static boolean getDebugMode ();

public static void setDebugMode (boolean debugMode);

The getDebugMode function returns true if the game is in test mode, and false if it isn’t. Pass true through the setDebugMode method to enable test mode, or false to disable it.

isSupported

Checks to see if the current device supports Unity Ads.

public static boolean isSupported ();

Returns true if the device supports Unity Ads, and false if it doesn’t.

getVersion

Returns the string version of this Unity Ads SDK.

public static String getVersion ();

isInitialized

Check whether Unity Ads has been initialized. This may be useful for debugging initialization problems.

public static boolean isInitialized ();

Returns true if Unity Ads is initialized, and false if it isn’t.

UnityMonetization

This is a static class that implements a delegate to deal with Placement statuses and content.

setListener

Sets the IUnityMonetizationListener listener for PlacementContent callback events.

public static void setListener (IUnityMonetizationListener listener);

getListener

Returns the current IUnityMonetizationListener listener for PlacementContent callback events.

public static IUnityMonetizationListener getListener ();

IUnityMonetizationListener

The developer implements this interface, and passes it to the SDK.

####onPlacementContentReady This function notifies you that a PlacementContent object is ready for a given Placement and ready to show.

onPlacementContentChanged

This function notifies you when the readied PlacementContent object’s status has changed due to a refresh.

Example IUnityMonetizationListener implementation
private class UnityMonetizationListener implements IUnityMonetizationListener {

    @Override
    public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
        // Check the Placement ID to determine behavior
        switch (placementId) {
            case "mixedPlacement":
                if (placementContent instanceof PromoAdPlacementContent) {
                    PromoAdPlacementContent promoPlacementContent = ((PromoAdPlacementContent) placementContent)
                    // Promo content is ready, prepare Promo display
                } else if (placementContent instanceof ShowAdPlacementContent) {
                    ShowAdPlacementContent adPlacementContent = ((ShowAdPlacementContent) placementContent);
                    // Ad content is ready, prepare video ad display
                }
                break;
            case "rewardedVideo":
                if (placementContent instanceof ShowAdPlacementContent) {
                    ShowAdPlacementContent adPlacementContent = ((ShowAdPlacementContent) placementContent);
                    if (adPlacementContent.isRewarded ()) {
                        // Rewarded content is ready, prepare content for display and implement reward handlers 
                    }
                }
                break;
        }
    }

    @Override
    public void onPlacementContentStateChange (String placementId, PlacementContent placementContent, UnityMonetization.PlacementContentState previousState, UnityMonetization.PlacementContentState newState) {
    }
}

isReady

Checks whether a PlacementContent object is ready for the given Placement. Returns true if content is ready, and false if it isn’t.

public static boolean isReady (String placementId);

getPlacementContent

Returns the PlacementContent that is ready for the given Placement. Returns null if no content is ready.

public static PlacementContent getPlacementContent (String placementId);

You can extend this function to cast the returned PlacementContent as a specific type. If the returned content is of a different type, it returns null.

public static <T extends PlacementContent> T getPlacementContent (String placementId, Class<T> asClass);

The asClass parameter represents the type you wish to cast to.

PlacementContent

An object representing monetization content that your Placement can display.

isReady

This function returns true if the PlacementContent is ready to display, and false if it isn’t.

public boolean isReady ();

getType

This function returns the type of PlacementContent available to display.

public String getType ();

The following string values are valid:

String value Description
SHOW_AD Refers to video ad content using the ShowAdPlacementContent class extension.
PROMO_AD Refers to IAP Promo content using the PromoAdPlacementContent class extension.
NO_FILL Refers to a lack of PlacementContent available for the specified Placement.

RewardablePlacementContent

Extends the PlacementContent class with functionality to support rewarded content.

isRewarded

This function returns true if the PlacementContent is rewarded, and false if it isn’t.

public boolean isRewarded ();

ShowAdPlacementContent

Extends the RewardablePlacementContent class with functionality to support video ad content.

show

This function displays the available ShowAdPlacementContent. Implement an IShowAdListener interface to define how this function responds to each ad FinishState.

public void show (Activity activity, IShowAdListener listener);

IShowAdListener

Implement this interface to provide the onAdsFinished callback method for a video ad’s FinishState.

onAdsFinished

Implement this method to provide logic for handling whether the ad was completed, skipped, or errored out.

void onAdFinished (String placementId, UnityAds.FinishState withState);
FinishState

An enum representing the final state of an ad when finished. Use it to handle reward cases.

Value Description
COMPLETED The player viewed the ad in its entirety.
SKIPPED The player skipped the ad before it played in its entirety.
ERROR The ad failed to load.
Example onAdsFinished implementation
@Override
public void onAdFinished (String s, UnityAds.FinishState finishState) {
    Log.d ("PlacementId: " + s + " " + finishState);

    if (finishState == UnityAds.FinishState.COMPLETED) {
        if (s.equals (rewardedPlacementId)) {
            // Reward the player here.
        }
    } else if (finishState == UnityAds.FinishState.SKIPPED) {
        // Optionally implement skipped logic
    } else if (finishState == UnityAds.FinishState.ERROR) {
        // Optionally attempt to retrieve another ad
    }
}

PromoAdPlacementContent

Extends the ShowAdPlacementContent class, providing functionality for IAP Promo content. For more information, see documentation on Native Promo.

UnityBanners

A static class for handling, showing and hiding ad banners.

loadBanner

The basic method for loading banner ad content. You can adjust this function with several parameters, depending on your needs.

Method Description
public static void loadBanner (Activity activity) Loads the banner ad with the default Placement ID (as defined in the Developer Dashboard).
public static void loadBanner (final Activity activity, final String placementId) Loads the banner ad with a specific Placement ID.

destroy

Destroys the banner ad, removing it from the Activity hierarchy and hiding it from the player.

public static void destroy ();

setBannerListener and getBannerListener

Sets or retrieves the assigned IUnityBannerListener for Unity Ads to send banner callbacks to.

public static void setBannerListener (IUnityBannerListener listener);

public static IUnityBannerListener getBannerListener ();

IUnityBannerListener

Implement this interface for callbacks and pass it to the SDK.

onUnityBannerLoaded

This callback fires when the banner ad is loaded and available to show, where view is the View to be placed in the view hierarchy.

void onUnityBannerLoaded (String placementId, View view);
onUnityBannerUnloaded

This callback fires on destroy, notifying that the banner was completely destroyed and references can be removed (for example, removing the view provided in onUnityBannerLoaded).

void onUnityBannerUnloaded (String placementId);
onUnityBannerShow

This callback fires when the banner ad entered the view hierarchy and is visible to the player.

void onUnityBannerShow (String placementId);
onUnityBannerHide

This callback fires when the banner ad is hidden from the player, due to removal from the view hierarchy or the window changing.

void onUnityBannerHide (String placementId);
onUnityBannerClick

This callback fires when the player clicks the banner ad.

void onUnityBannerClick (String placementId);
onUnityBannerError

This callback fires when the SDK encounters an error. All errors are logged, but this method provides an additional debugging aid. You can also use this callback to collect statistics from different error scenarios.

void onUnityBannerError (String message);
Example IUnityBannerListener implementation
final IUnityBannerListener unityBannerListener = new UnityBannerListener ();

UnityBanners.setBannerListener (unityBannerListener);

private class UnityBannerListener implements IUnityBannerListener {

        @Override
        public void onUnityBannerLoaded (String placementId, View view) {
            bannerView = view;
            ((ViewGroup) findViewById (R.id.unityads_example_layout_root)).addView (view);
            toast ("onUnityBannerLoaded", "Banner loaded");
        }

        @Override
        public void onUnityBannerUnloaded (String placementId) {
            toast ("onUnityBannerUnloaded", placementId + " unloaded");
            bannerView = null;
        }

        @Override
        public void onUnityBannerShow (String placementId) {
            toast ("onUnityBannerShow", placementId + " show");
        }

        @Override
        public void onUnityBannerClick (String placementId) {
            toast ("onUnityBannerShow", placementId + " click");
        }

        @Override
        public void onUnityBannerHide (String placementId) {
            toast ("onUnityBannerHide", placementId + " hide");
        }

        @Override
        public void onUnityBannerError (String message) {
            toast ("onUnityBannerError", "Banner error: " + message);
        }
    }
}

Back to top

Still need help? Get in touch!
Last updated on 16th Nov 2018