Knowledge base

Integration guide for Android (Java)

Overview

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

  • If you are an iOS developer using Objective-C, click here.
  • If you are a Unity developer using C#, click here.
  • Click here for the Android (Java) API reference.

In this guide:

Basic ads 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 Unity Dashboard.
  2. From the landing page, navigate to the Monetize service. Click Explore to launch the Monetize Dashboard.
  3. Select Projects from the navigation bar.
  4. Click the New Project button.

Locate your Project’s Game ID by selecting your Project, then selecting Project Settings from the navigation bar. From the Project Settings page, go to the Game IDs section. Copy the Google Play Store Game ID, as you will need it to activate the Unity Ads service in your game.

Creating Ad Units in your game

Ad Units are surfacing points that trigger ads in your game. Create Ad Units in the Monetize Dashboard by selecting your project, then selecting Monetization > Ad Units from the navigation bar.

Click the Add Ad Unit button to bring up the creation modal. Enter your Ad Unit ID and select its type:

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

Every Unity Ads-enabled project has one Ad Unit for each format (rewarded, interstitial, and banner) per platform by default. Feel free to use one of these for your first implementation if they suit your needs, or create your own.

For more information, see documentation on Ad Units.

Importing the Unity Ads framework

Download the Unity Ads framework here, specifically unity-ads.aar.

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.ads.IUnityAdsListener;
import com.unity3d.ads.UnityAds;

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 Monetize Dashboard by selecting the Project, then selecting Project Settings from the navigation bar (see the Dashboard guide section on Project Settings for details).

In your game script, you’ll need to implement an IUnityAdsListener interface that handles ad callbacks. The initialize method to initialize the SDK requires this listener as a parameter. Initialize the SDK early in your game’s run-time life cycle, before you need to show ads. For example:

import com.unity3d.ads.IUnityAdsListener;
import com.unity3d.ads.UnityAds;

public class InitializeAdsScript extends AppCompatActivity implements View.OnClickListener, IUnityAdsListener {

    private String unityGameID = "1234567";
    private Boolean testMode = true;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        // Declare a new listener:
        final UnityAdsListener myAdsListener = new UnityAdsListener ();
        // Add the listener to the SDK:
        UnityAds.addListener(myAdsListener);
        // Initialize the SDK:
        UnityAds.initialize (this, unityGameID, testMode);
    }

    // Implement the IUnityAdsListener interface methods:
    private class UnityAdsListener implements IUnityAdsListener {

        @Override
        public void onUnityAdsReady (String adUnitId) {
            // Implement functionality for an ad being ready to show.
        }

        @Override
        public void onUnityAdsStart (String adUnitId) {
            // Implement functionality for a user starting to watch an ad.
        }

        @Override
        public void onUnityAdsFinish (String adUnitId, UnityAds.FinishState finishState) {
            // Implement functionality for a user finishing an ad.
        }

        @Override
        public void onUnityAdsError (UnityAds.UnityAdsError error, String message) {
            // Implement functionality for a Unity Ads service error occurring.
        }
    }
}

For the initialize function, the myActivity parameter is the current Android Activity. The unityGameID variable is the Unity Game ID for you Project, found in the developer dashboard. The myAdsListener variable is the listener for IUnityAdsListener callbacks. The true boolean indicates that the game is in test mode, and will only show test ads.

Note: You must implement each of the callback methods in the listener interface, even if they are empty functions for now. You will populate them with the appropriate logic where needed in the following sections. For more information on each listener callback method, see documentation on IUnityAdsListener API.

Interstitial display ads

To display a full-screen interstitial ad using the Advertisements API, simply initialize the SDK and use the Show function with the desired Ad Unit ID.

Interstitial ads example

import com.unity3d.ads.IUnityAdsListener;
import com.unity3d.ads.UnityAds;

public class ShowInterstitialAds extends AppCompatActivity implements View.OnClickListener, IUnityAdsListener {

    private String unityGameID = "1234567";
    private Boolean testMode = true;
    private String adUnitId = "video";

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        // Declare a new listener:
        final UnityAdsListener myAdsListener = new UnityAdsListener ();
        // Add the listener to the SDK:
        UnityAds.addListener(myAdsListener);
        // Initialize the SDK:
        UnityAds.initialize (this, unityGameID, testMode);
    }

    // Implement a function to display an ad if the Ad Unit is ready:
    public void DisplayInterstitialAd () {
        if (UnityAds.isReady (adUnitId)) {
            UnityAds.show (this, adUnitId);
        }
    }

    // Implement the IUnityAdsListener interface methods:
    private class UnityAdsListener implements IUnityAdsListener {

        @Override
        public void onUnityAdsReady (String adUnitId) {
            // Implement functionality for an ad being ready to show.
        }

        @Override
        public void onUnityAdsStart (String adUnitId) {
            // Implement functionality for a user starting to watch an ad.
        }

        @Override
        public void onUnityAdsFinish (String adUnitId, UnityAds.FinishState finishState) {
            // Implement functionality for a user finishing an ad.
        }

        @Override
        public void onUnityAdsError (UnityAds.UnityAdsError error, String message) {
            // Implement functionality for a Unity Ads service error occurring.
        }
    }
}

In this example, you can invoke DisplayInterstitialAd from anywhere in your game you wish to show an interstitial ad.

Rewarded video 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 completing a video ad, use the onUnityAdsFinish listener callback method’s FinishState result to check if the user finished watching the ad and should be rewarded.

Rewarded video example

import com.unity3d.ads.IUnityAdsListener;
import com.unity3d.ads.UnityAds;

public class ShowRewardedAds extends AppCompatActivity implements View.OnClickListener, IUnityAdsListener {

    private String unityGameID = "1234567";
    private Boolean testMode = true;
    private String adUnitId = "rewardedVideo";

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        // Declare a new listener:
        final UnityAdsListener myAdsListener = new UnityAdsListener ();
        // Add the listener to the SDK:
        UnityAds.addListener(myAdsListener);
        // Initialize the SDK:
        UnityAds.initialize (this, unityGameID, testMode);
    }

    // Implement a function to display an ad if the Ad Unit is ready:
    public void DisplayRewardedVideoAd () {
        if (UnityAds.isReady (adUnitId)) {
            UnityAds.show (this, adUnitId);
        }
    }

    // Implement the IUnityAdsListener interface methods:
    private class UnityAdsListener implements IUnityAdsListener {

        public void onUnityAdsReady (String adUnitId) {
            // Implement functionality for an ad being ready to show.
        }

        @Override
        public void onUnityAdsStart (String adUnitId) {
            // Implement functionality for a user starting to watch an ad.
        }

        @Override
        public void onUnityAdsFinish (String adUnitId, UnityAds.FinishState finishState) {
            // Implement conditional logic for each ad completion status:
           if (finishState.equals(UnityAds.FinishState.COMPLETED) {
              // Reward the user for watching the ad to completion.
           } else if (result == FinishState.SKIPPED) {
              // Do not reward the user for skipping the ad.
           } else if (result == FinishState.ERROR) {
              // Log an error.
           }
        }

        @Override
        public void onUnityAdsError (UnityAds.UnityAdsError error, String message) {
            // Implement functionality for a Unity Ads service error occurring.
        }
    }
}

Rewarded video ad buttons

Using a button to allow the player to opt in to watching an ad is a common implementation for rewarded video ads. Use the example code below to create a rewarded ads button. The ads button displays an ad when pressed, as long as ads are available. For information on configuring buttons, see Android's documentation.

Once you've implemented your button, add a script with the following code, where showAdButton is a button configured in the View:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.unity3d.ads.IUnityAdsListener;
import com.unity3d.ads.UnityAds;

public class MainActivity extends AppCompatActivity {

    private String unityGameID = "1234567";
    private Boolean testMode = true;
    private String adUnitId = "rewardedVideo";
    private Button rewardedButton;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        // Declare a new listener:
        final UnityAdsListener myAdsListener = new UnityAdsListener ();
        //Add the listener to the SDK:
        UnityAds.addListener(myAdsListener);
        // Initialize the SDK:
        UnityAds.initialize (this, unityGameID, testMode);

        // Find the button in the view hierarchy and set its click function to show ads:
        rewardedButton = findViewById (R.id.showAdButton);
        rewardedButton.setOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                DisplayRewardedAd ();
                rewardedButton.setEnabled (false);
            }
        });
    }

    // Implement a function to display an ad if the Ad Unit is ready:
    public void DisplayRewardedAd () {
        if (UnityAds.isReady (adUnitId)) {
            UnityAds.show (this, adUnitId);
        }
    }

    // Implement the IUnityAdsListener interface methods:
    private class UnityAdsListener implements IUnityAdsListener {

        public void onUnityAdsReady (String adUnitId) {
            // Implement functionality for an ad being ready to show.
            rewardedButton.setEnabled (true);
        }

        @Override
        public void onUnityAdsStart (String adUnitId) {
            // Implement functionality for a user starting to watch an ad.
        }

        @Override
        public void onUnityAdsFinish (String adUnitId, UnityAds.FinishState finishState) {
            // Implement conditional logic for each ad completion status:
            if (finishState.equals(UnityAds.FinishState.COMPLETED)) {
                // Reward the user for watching the ad to completion.
            } else if (finishState.equals(UnityAds.FinishState.SKIPPED)) {
                // Do not reward the user for skipping the ad.
            } else if (finishState.equals(UnityAds.FinishState.ERROR)) {
                // Log an error.
            }
        }

        @Override
        public void onUnityAdsError (UnityAds.UnityAdsError error, String message) {
            // Implement functionality for a Unity Ads service error occurring.
        }
    }
}

Ad Unit configuration

Banner ads require a specific type of dedicated banner Ad Unit.

app-ads.txt

app-ads.txt is an IAB initiative to combat fraud and create transparency in the advertising ecosystem. Be sure to implement app-ads.txt as described. Otherwise, banner demand may be significantly decreased.

Script implementation

Note: You must initialize Unity Ads before displaying a banner ad.

In your game script, import the BannerView API, then implement an IListener interface to provide callbacks to the SDK. The following script sample is an example implementation for displaying two banner ads on the screen, and buttons for testing them. For more information on the classes referenced, see the BannerView API section.

package com.example.test_app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.unity3d.ads.UnityAds;
import com.unity3d.services.banners.BannerView;
import com.unity3d.services.banners.UnityBannerSize;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {

    String unityGameID = "3054608";
    Boolean testMode = true;
    Boolean enableLoad = true;
    String adUnitId = "banner";
    // Listener for banner events:
    UnityBannerListener bannerListener = new UnityBannerListener();
    // This banner view object will be placed at the top of the screen:
    BannerView topBanner;
    // This banner view object will be placed at the bottom of the screen:
    BannerView bottomBanner;
    // View objects to display banners:
    RelativeLayout topBannerView;
    RelativeLayout bottomBannerView;
    // Buttons to show the banners:
    Button showTopBannerButton;
    Button showBottomBannerButton;
    // Buttons to destroy the banners:
    Button hideTopBannerButton;
    Button hideBottomBannerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initialize Unity Ads:
        UnityAds.initialize (this, unityGameID, null, testMode, enableLoad);

        // Set up a button to load the top banner when clicked:
        showTopBannerButton = findViewById(R.id.loadTopBanner);
        showTopBannerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTopBannerButton.setEnabled(false);
                // Create the top banner view object:
                topBanner = new BannerView(view.getContext(), adUnitId, new UnityBannerSize(320, 50));
                // Set the listener for banner lifcycle events:
                topBanner.setListener(bannerListener);
                // Request a banner ad:
                topBanner.load();
                // Get the banner view:
                topBannerView = findViewById(R.id.topBanner);
                // Associate the banner view object with the banner view:
                topBannerView.addView(topBanner);
            }
        });

        // Set up a button to load the bottom banner when clicked:
        showBottomBannerButton = findViewById(R.id.loadBottomBanner);
        showBottomBannerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBottomBannerButton.setEnabled(false);
                bottomBanner = new BannerView(view.getContext(), adUnitId, new UnityBannerSize(320, 50));
                bottomBanner.setListener(bannerListener);
                bottomBannerView = findViewById(R.id.bottomBanner);
                bottomBannerView.addView(bottomBanner);
                bottomBanner.load();
            }
        });

        // Set up a button to destroy the top banner when clicked:
        hideTopBannerButton = findViewById(R.id.hideTopBanner);
        hideTopBannerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Remove content from the banner view:
                topBannerView.removeAllViews();
                // Remove the banner variables:
                topBannerView = null;
                topBanner = null;
                showTopBannerButton.setEnabled(true);
            }
        });

        // Set up a button to destroy the bottom banner when clicked:
        hideBottomBannerButton = findViewById(R.id.hideBottomBanner);
        hideBottomBannerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomBannerView.removeAllViews();
                bottomBannerView = null;
                bottomBanner = null;
                showBottomBannerButton.setEnabled(true);
            }
        });
    }

    BannerView SetUpBanner(){
        return new BannerView(this, adUnitId, new UnityBannerSize(320, 50));
    }

    // Implement listener methods:
    private class UnityBannerListener implements BannerView.IListener {
        @Override
        public void onBannerLoaded(BannerView bannerAdView) {
            // Called when the banner is loaded.
        }

        @Override
        public void onBannerFailedToLoad(BannerView bannerAdView, BannerErrorInfo errorInfo) {
            Log.d("SupportTest", "Banner Error" + s);
            // Note that the BannerErrorInfo object can indicate a no fill (see API documentation).
        }

        @Override
        public void onBannerClick(BannerView bannerAdView) {
            // Called when a banner is clicked.
        }

        @Override
        public void onBannerLeftApplication(BannerView bannerAdView) {
            // Called when the banner links out of the application.
        }
    }
}

Note: This example uses a single listener for multiple banner view objects. You can also have a different listener for each banner view object.

You can place the banner view object into your view hierarchy, just like you would any other view. This allows you to customize the position of each banner instance, or display multiple banners.

Testing

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

  1. From the Monetize Dashboard, select your Project.
  2. Select Project Settings from the navigation bar.
  3. Scroll down to the Test Mode section, then edit the Google Play Store.
  4. Select the Override client test mode checkbox, then select the Force test mode ON for all devices 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.

Still need help? Get in touch!
Last updated on 22nd Oct 2021