Android SDK 450 Integration Guide

The InMobi Ad SDK 4.5 for Android contains the code necessary to integrate InMobi ads with your application. This SDK is designed to work across all Android platforms with a minimum OS version of 2.3.

Note: For video ads, the minimum OS requirement is Android version 4.x, or higher.

Getting Started

To get started with the integration, perform the following steps:

  1. Download the InMobi Ad Network SDK for Android by clicking here. This bundle also contains a sample app.
  2. Create your account. Instructions are available here.
  3. Register your property. Important: InMobi recommends that you create a different property ID for each ad type. For example, if you would like to show both banner and interstitial ads on your property, register it twice. Name the first property, say, 'your_property_banner' and the second, 'your_property_interstitial'.
  4. Go to the Properties tab and click the spanner icon next to your property to get your property ID. Copy this value and use it in the integration code.
    Important: After clicking the spanner icon, you will see Slots in the left navigation area. Note that these slots are not for monetization; they pertain to actions using InMobi analytics.

Notes:

  1. You require a valid property (app/site) URL to monetize with InMobi.
  2. All references to app ID and/or site ID refer to property ID.

Configuration

Adding the SDK to your Project

  1. Download the InMobi SDK for Android by clicking the Download Now link, above.
  2. Copy the InMobi-4.x.x.jar file to your project by performing the steps given below.
    1. Create a subdirectory named libs in the root directory of your project. This will already be done for you if you have used Android's activityCreator tool.
    2. Copy the InMobi-4.x.x.jar file into the libs directory.

To add the JAR files to your project, perform the following steps:

  1. Right-click your project from the Package Explorer tab.
  2. Select Properties.
  3. Select Java Build Path from the left navigation area.
  4. Select the Libraries tab from the main window.
  5. Click Add JARs...
  6. Select the InMobi-4.x.x.jar file that you copied earlier to the libs directory.
  7. Click OK to add the InMobi SDK to your Android project.
  8. Install the Google Play Services SDK. Please see here for more information.
  9. Add the below ProGuard configuration. It is required as we use reflection to invoke Google Play Service methods. Please see here for information on validating your integration with Google Play Services.
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient{
    public *;
    }
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info{
    public *;
    }
    

Manifest File Changes

Follow these instructions to make changes to your Android manifest file.

Mandatory Inclusion

The InMobi Android SDK requires the Google Play Services, 4.0 or higher, library to function. This is to comply with the Google Play content guidelines for collecting the advertising identifier. Please see here for more information.

Include the below within the <application> tag.

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

Mandatory Activities

Ensure that you add the com.inmobi.androidsdk.IMBrowserActivity activity file to your AndroidManifest.xml within the <application> tag.

This activity will be used to open ads in the embedded browser, and to display interstitial ads.

<activity android:name="com.inmobi.androidsdk.IMBrowserActivity"
android:configChanges="keyboardHidden|orientation|keyboard|smallestScreenSize|screenSize" android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:hardwareAccelerated="true" />

Note: The smallestScreenSize and screenSize attributes are defined for Android OS 3.2 (API level 13) and above. If you are using an Android OS version earlier than 3.2, you do not have to add these attributes to the manifest file.

Recommended Broadcast Receiver

Ensure that you add the com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver broadcast receiver to your AndroidManifest.xml file within the <application> tag.

This IMAdTrackerReceiver will be used to track installs using the Google Play referrer.

<receiver
android:name="com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="com.inmobi.share.id" />
</intent-filter>
</receiver>

If you are using your own receiver to track INSTALL_REFERRER, please check the Setting the Referrer section under Tracking Installs.

Mandatory Permissions

Ensure that you add the INTERNET and ACCESS_NETWORK_STATE permissions to your AndroidManifest.xml file just before the closing </manifest> tag:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Recommended Permissions

Ensure that you add the permissions to your AndroidManifest.xml file just before the closing </manifest> tag:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>

Please see this article for details on how these permissions are used.

Hardware Acceleration

InMobi provides HTML5 video ads. To support this, hardware acceleration must be enabled. We recommend that publishers add the property android:hardwareAccelerated="true" in the application tag, or, alternatively, in all the activities that display InMobi ads.

Activity Recognition Service

If the application uses Google Play services, ad delivery can be optimized by allowing InMobi access to this service. This can be done by following these steps:

  1. Add the latest Google Play services JAR file to the project as per documentation mentioned here.
  2. Add permission to access the service by including the following line in the manifest:
    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" >
    
  3. Allow InMobi to register the service for activity recognition by adding the following line in the manifest under the 'application' tag.
    <service android:enabled="true" android:name="com.inmobi.commons.internal.ActivityRecognitionManager" />
    

Sample Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.inmobi.sample"
android:versionCode="9"
android:versionName="1.8" >
<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" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:hardwareAccelerated="true" > 
<service
android:name="com.inmobi.commons.internal.ActivityRecognitionManager"
android:enabled="true" />
<receiver
android:name="com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="com.inmobi.share.id" />
</intent-filter>
</receiver>
<activity
android:name="com.gomob.di.qa.analytics.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.inmobi.androidsdk.IMBrowserActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|smallestScreenSize|screenSize" android:hardwareAccelerated="true" />
<activity
android:name="com.gomob.di.qa.analytics.activity.PublisherAPI"
android:label="@string/title_activity_publisher_api" >
</activity>
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>

Initializing the InMobi SDK

The property ID is your app’s unique identifier. Use this property ID (app ID/site ID) when integrating with the InMobi SDK.

IMPORTANT: The property ID used to initialize the SDK will be used for all Analytics reporting. It is mandatory to initialize the SDK at app launch. The initialize API must be invoked on the UI Thread, preferably in the onCreate method of the launcher activity.

Go to the Properties tab and click the spanner icon next to your property to get your property ID.

InMobi.initialize(activity, "YOUR_PROPERTY_ID");

Banner Ad

Banner ads are the most common ad format. They consist of an image with a hyperlink that takes the user to a website. These ads display either statically on the page, or sometimes with an incorporated animation. Banners are small ads that, when clicked, typically take the user to some form of a full screen, in-app browsing experience.

Banner Interface

Method 1: Adding an IMBanner instance to XML layout

You can add an IMBanner to your activity through layout XML files. Add the XML snippet in your layout XML file to start receiving ads.

Example: If you want an ad of size 320x50, add the XML attribute shown below to your parent ViewGroup:

<com.inmobi.monetization.IMBanner android:layout_width="320dp"
android:layout_height="50dp" android:id="@+id/banner"
adSize="15" appId="Your-Property-ID" />

When the activity is loaded, the banner ad is loaded automatically.

The XML code snippet builds the IMBanner object. This object can be referenced programmatically using Activity’s findViewById method. Ads can be loaded at will using the loadBanner method of IMBanner.

Example: IMBanner banner = (IMBanner) findViewById(R.id.banner);

Loading Banner Ads

To load a banner ad, use the method shown below:

banner.loadBanner();

CAUTION: The adSlot attribute from the XML has been renamed to adSize in SDK 3.6.0 onwards.

Note: The adSize is 15 (320x50) by default; any invalid value will default to adSize 15.

Supported Banner Sizes

Select an adSize from the following set of values declared in IMBanner.

Size

adSize value

Variable name under IMBanner

300x250

10

INMOBI_AD_UNIT_300x250

728x90

11

INMOBI_AD_UNIT_728x90

468x60

12

INMOBI_AD_UNIT_468x60

320x50

15

INMOBI_AD_UNIT_320x50

Setting the Listener

If you need ad status notifications, you need to implement the IMBannerListener interface and register the instance with IMBanner.

banner.setIMBannerListener(new IMBannerListener() {
@Override
public void onShowBannerScreen(IMBanner arg0) {
}
@Override
public void onLeaveApplication(IMBanner arg0) {
}
@Override
public void onDismissBannerScreen(IMBanner arg0) {
}
@Override
public void onBannerRequestFailed(IMBanner banner, IMErrorCode errorCode) {
}
@Override
public void onBannerRequestSucceeded(IMBanner arg0) {
}
@Override
public void onBannerInteraction(IMBanner arg0, Map<String, String> arg1) {
}
});

The following callbacks are received by the listener:

  • onBannerRequestSucceeded: Banner ad request successful.
  • onBannerRequestFailed: Banner ad request failed. The IMErrorCode object contains the error description.
  • onShowBannerScreen: Called when ad expands on top of the screen because of user action.
  • onDismissBannerScreen: Called when the expanded ad comes back to its original position because of action such as the user closing the ad.
  • onLeaveApplication: Called when click on the ad results in exiting the application context.
  • onBannerInteraction: Called when the banner is tapped or interacted with by the user.

After the IMBanner instance is created, configurations such as testing mode and auto refresh control can be done as described in the Advanced Settings, below.

Method 2: Creating the IMBanner Instance

To create the IMBanner instance programmatically, perform the following steps:

1. Import the com.inmobi.monetization package in your activity. Then create an instance of IMBanner by providing the activity, appId, and adSize.

IMBanner imbanner = new IMBanner(activity, “YOUR-PROPERTY-ID”,IMBanner.INMOBI_AD_UNIT_320X50

Note: InMobi cannot serve ads if the following are invalid:

  • activity
  • appId
  • adSize(one of the adSize constants given in the IMBanner)

2. Get the parent layout to where the IMBanner must be added.

LinearLayout parent = (LinearLayout)findViewById(R.id.linearLayoutParent);

3. Add the IMBanner to the parent view.

parent.addView(banner);

Testing the Integration

Set your property in test mode as described here.

Advanced Settings

Setting Auto Refresh

After you add the IMBanner to the parent ViewGroup, the ad refresh will start automatically. The default refresh interval is 60 seconds.

You can set the refresh interval using the following method:

banner.setRefreshInterval(120);

To switch off the auto refresh feature, use the method shown here:

banner.setRefreshInterval(IMBanner.REFRESH_INTERVAL_OFF);

To manually load a new ad, use the method shown here:

banner.loadBanner();

Setting an Optimal Slot Value

When creating a universal app, or an app that is designed for both tablets and smart phones, the following code returns a slot value optimal for display within the app. It takes into account device properties like screen resolution, screen pixel density, and orientation. An optimal slot has proven to increase CTRs, and correspondingly eCPMs.

Include the function below in your code and call the function when requesting an ad.

public static Integer getOptimalSlotSize(Activity ctxt) {
Display display = ((WindowManager) ctxt
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
double density = displayMetrics.density;
double width = displayMetrics.widthPixels;
double height = displayMetrics.heightPixels;
int[][] maparray = { { IMBanner.INMOBI_AD_UNIT_728X90, 728, 90 }, {
IMBanner.INMOBI_AD_UNIT_468X60, 468, 60 }, {
IMBanner.INMOBI_AD_UNIT_320X50, 320, 50 } };
for (int i = 0; i < maparray.length; i++) {
if (maparray[i][1] * density <= width
&& maparray[i][2] * density <= height) {
return maparray[i][0];
}
}
return IMBanner.INMOBI_AD_UNIT_320X50;
}

Initialize and use the above method as shown here:

private IMBanner imbanner = new IMBanner(activity, “YOUR-PROPERTY-ID”, getOptimalSlotSize(activity));

Interstitial / Native Interstitial Ad

Interstitial ads are full screen ads (either static image or video) that are modal in nature. They appear to users either before the launch of an application or at transition points, such as between game levels, or between the homepage and a unique content page. The richer nature of these ads makes them more expensive and subject to impression constraints.

InMobi serves both landscape and portrait type of interstitial ads. The InMobi SDK will automatically ensure that it serves appropriate ads as per the application orientation.

In order to implement a native frame for your interstitial property, please refer to our help article on Native Interstitials.

Interstitial State Flow

Upon request, an interstitial ad can be in one of the following states:

  • init
  • loading
  • ready
  • active
  • unknown
  1. The first time IMInterstitial is instantiated, the ad will be in the init state.
  2. When a request for loading the ad is made, the ad moves to the loading state.
  3. When the ad is ready to be displayed, the ad state changes to ready.
  4. At this point, a request for displaying the ad can be made.
  5. The ad moves to the active state when it is displayed to the user.
  6. When the user closes the ad, the ad moves back to the init state.
  7. The interstitial is in the unknown state when its state cannot be determined natively.

Getting an Interstitial Ad

While configuring the SDK, you have already initialized the InMobi SDK with the appropriate property ID. Continue to use the same property ID with the interstitial integration. If you have missed this configuration step, InMobi will fail to load the interstitial ad.

The IMInterstitial class is used to request interstitial ads.

Step 1: Importing the com.inmobi.monetization package in your activity.

Step 2: Creating an interstitial instance.

IMInterstitial interstitial = new IMInterstitial(activity, “YOUR-PROPERTY-ID”)

Step 3: Loading the interstitial ad.

Load the interstitial ad by calling the following method:

interstitial.loadInterstitial();

Step 4: Showing the interstitial ad.

Render the interstitial ad after getting the callback onInterstitialLoaded; by calling the following method:

if (interstitial.getState() ==IMInterstitial.State.READY)
interstitial.show();

Note: You will need to invoke the loadInterstitial() method again before making a call to show(). Make sure that the current state of the interstitial ad is ready before making the call. Otherwise, an IllegalStateException is generated.

Setting the Interstitial Listener

If you need ad status notification, implement the IMInterstitialListener interface and register the instance with IMInterstitial.

interstitial.setIMInterstitialListener(new IMInterstitialListener() {
public void onShowInterstitialScreen(IMInterstitial arg0) {
}
@Override
public void onLeaveApplication(IMInterstitial arg0) {
}
@Override
public void onDismissInterstitialScreen(IMInterstitial arg0) {
}
@Override
public void onInterstitialLoaded(IMInterstitial arg0) {
}
@Override
public void onInterstitialInteraction(IMInterstitial interstitial, Map<String, String> params) {	
}
@Override
public void onInterstitialFailed(IMInterstitial arg0, IMErrorCode arg1) {
}
});

The following callbacks are sent to the listener:

  • onInterstitialLoaded - Interstitial ad loaded successfully.
  • onInterstitialFailed - Interstitial ad request failed. The IMAdMError object contains the error description.
  • onShowInterstitialScreen - Interstitial ad rendered successfully as full screen.
  • onDismissInterstitialScreen - Interstitial ad closed due to user action such as click on close, or back press, and so on.
  • onLeaveApplication - Called when click on the ad results in exiting the application context.
  • onInterstitialInteraction - Called when the interstitial is tapped or interacted with by the user.

Testing the Integration

Set your property in test mode as described here.

Native Content Ads

Native ads are ads that are rendered by publishers, allowing them to give users a unique experience.

A native ad consists of ad assets in a publisher-specified format. Common assets include the image URL associated with the ad, icon URLs of the ad, if any, and texts like title, subtitle, and description. For creating specific templates for your app layout, please see our help article.

Initializing the InMobi SDK

Initialize your InMobi SDK before creating a native ad.

InMobi.initialize(activity, "YOUR_PROPERTY_ID");

Setting Publisher Content

For creating specific templates for your app layout, please see our help article.

Creating a Native Instance

To create the IMNative instance, perform the following steps:

  1. Import the com.inmobi.monetization package in your activity.
  2. Create an instance of IMNative by providing the IMNativeListener as a parameter to the class constructor.

Use this code to integrate:

IMNative nativeAd = new IMNative(nativeListener);

The property ID provided at the time of initializing will be used to make the ad request in the above native ad instance.

If your app needs to support multiple property IDs, create an instance of native ad by providing the PROPERTY_ID and IMNativeListener as parameters, like the below:

IMNative nativeAd = new IMNative(“YOUR-PROPERTY-ID”, nativeListener);

Invoke loadAd on the native ad instance to request a native ad. The loadAd API will return a success or failure callback on the native ad listener. Upon receiving a failed callback, check the error code for any integration issues, like the below:

nativeAd.loadAd()

Implementing a Native Ad Listener

Implement the IMNativeListener to get success or failure callbacks for the native ad request. Pass this listener instance to the native ad instance mentioned in the previous step.

IMNativeListener provides two methods to be implemented.

Method One

-public void onNativeRequestSucceeded(IMNative nativeAd)
  • Native ad notifies the listener that it is ready.
  • Access the ad assets by getting ad content from the native ad instance.
    String pubContent = nativeAd.getContent()
  • The pubContent will be in the same format that the publisher has configured in the portal.

Method Two

-public void onNativeRequestFailed(IMErrorCode errorCode)
  • Native ad notifies the listener that an error has been encountered while trying to load.
  • Check the errorCode for details on the error.

Below is the code snippet for listener implementation:

IMNativeListener nativeListener = new IMNativeListener() {
@Override
public void onNativeRequestSucceeded(IMNative nativeAd) {
if (nativeAd != null)
{
nativeAd.getContent();	
}
}
@Override
public void onNativeRequestFailed(IMErrorCode errorCode) {
android.util.Log.e("TAG", "native ad failed");
}
});

Requesting a Native Ad

Invoke loadAd on the native ad instance to request a native ad. The loadAd API will return success or failure callback on the native ad listener. Upon receiving a failed callback, check the error code for any integration issues.

nativeAd.loadAd()

Getting Ad Content

Upon receiving a success callback, get the ad content from the native ad instance received in the callback.

nativeAd.getContent();

Tracking impressions

Render the native ad content and call the attachToView API on the same native ad instance by passing the rendered view as parameter. This is done to enable as impressions to be reported. This method will fail if the ad is not yet loaded, is already attached to a view, or is detached from a view.

nativeAd.attachToView(ViewGroup view);

Note: If you are rendering the native ad as part of a ListView, then you must pass the row view as a parameter to the attachToView API, and not the entire ListView object. Passing a ListView will cause the method to fail, and an error log to be printed.

Tracking Clicks

When the view that was rendered from the content of the ad is clicked, report this click to the native ad instance by calling handleClick. This gives publishers a convenient way to report gestures considered as clicks. The params dictionary can contain additional information that the publisher wants to provide as part of the click to the native instance.

nativeAd.handleClick(params);

Handling the Landing Page

If the getContent API returns the publisher content with a landing page field, you must handle the landing page of the native ad after calling handleClick method.

The landing page will be present with the key "landing_url". Also, the landing page URL will open externally.

Below is the code required to handle the landing page:

if (landingUrl != null){
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse(landingUrl));
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(browserIntent);
}

Note: If the "landing_url" key is NULL, InMobi will take appropriate action to open the landing page URL.

Cleaning Up the Native Ad Instance

When the native ad is no longer needed, detach the native ad from the view it was added to. This will clean up the native ad instance.

nativeAd.detachFromView();

Reloading a Native Ad

If detached from a view, a native ad instance cannot be reused. To make it reusable, the instance has to be reloaded.

  • Call loadAd again to reload the ad.
  • Follow the steps below:
    1. Load the native ad.
    2. Attach a view to the native ad
    3. Report clicks.
    4. When done with the ad, detach the view from native ad.

Rewarded Ads

IMPORTANT: Make video ad requests well before when the ad needs to be displayed. This is to cache the ad, providing a smooth and uninterrupted user.

Example: If you want to show the rewarded video ad at the end of a level (in a gaming app), request for the ad when the level begins.

Reward ads are full screen ads that provide a reward to the user upon the completion of a certain action. The reward is provided by the publisher after the user completes the action on the ad. The actions currently supported are Watching a Video, or interacting with a Playable Ad.

Reward ads are great because of the below 3 reasons:

  1. They are a strong retention hook for your users, keeping them engaged with your game/app for a longer time.
  2. They have a clear, opted-in user experience.
  3. They are an important source of monetization apart from in-app purchases and ads, and hence increase your overall revenues.

Reward Ad State Flow

Upon request, a reward ad can be in one of the following states:

  • init
  • loading
  • ready
  • active
  • unknown
  1. The first time IMInterstitial is instantiated, the ad will be in the init state.
  2. When a request for loading the ad is made, the ad moves to the loading state.
  3. When the ad is ready to be displayed, the ad state changes to ready.
  4. At this point, a request for displaying the ad can be made.
  5. The ad moves to the active state when it is displayed to the user.
  6. When the user closes the ad, the ad moves back to the init state.
  7. The reward ad is in the unknown state when its state cannot be determined natively.

Getting a Reward Ad

While configuring the SDK, you have already initialized the InMobi SDK with the appropriate property ID. Continue to use the same property ID with the reward ad integration. If you have missed this configuration step, InMobi will fail to load the reward ad.

The IMInterstitial class is used to request reward ads.

Step 1: Import the com.inmobi.monetization package in your activity.

Step 2: Creating an reward instance.

IMInterstitial rewardedAd = new IMInterstitial(activity, “YOUR-PROPERTY-ID”)

Step 3: Loading the reward ad.

Load the reward ad by calling the following method:

rewardedAd.loadInterstitial();

Step 4: Showing the reward ad.

Render the reward ad after getting the callback onInterstitialLoaded; by calling the following method:

if (rewardedAd.getState() ==IMInterstitial.State.READY)
rewardedAd.show();

Note: You will need to invoke the loadInterstitial() method again before making a call to show(). Make sure that the current state of the reward ad is ready before making the call. Otherwise, an IllegalStateException is generated.

Setting the Interstitial Listener

If you need ad status notification, implement the IMInterstitialListener interface and register the instance with IMInterstitial.

interstitial.setIMInterstitialListener(new IMInterstitialListener() {
public void onShowInterstitialScreen(IMInterstitial arg0) {
}
@Override
public void onLeaveApplication(IMInterstitial arg0) {
}
@Override
public void onDismissInterstitialScreen(IMInterstitial arg0) {
}
@Override
public void onInterstitialLoaded(IMInterstitial arg0) {
}
@Override
public void onInterstitialInteraction(IMInterstitial interstitial, Map<String, String> params) {	
}
@Override
public void onInterstitialFailed(IMInterstitial arg0, IMErrorCode arg1) {
}
});

The following callbacks are sent to the listener:

  • onInterstitialLoaded - Interstitial ad loaded successfully.
  • onInterstitialFailed - Interstitial ad request failed. The IMAdMError object contains the error description.
  • onShowInterstitialScreen - Interstitial ad rendered successfully as full screen.
  • onDismissInterstitialScreen - Interstitial ad closed due to user action such as click on close, or back press, and so on.
  • onLeaveApplication - Called when click on the ad results in exiting the application context.
  • onInterstitialInteraction - Called when the interstitial is tapped or interacted with by the user.

Setting the Reward Ads Listener

To get the status of the reward ads, implement the rewarded ads listener. This listener will give you callback when the user completes the reward action.

Import com.inmobi.monetization.IMIncentivisedListener;

rewardedAd.setIMIncentivisedListener(new IMIncentivisedListener() {
@Override
public void onIncentCompleted(IMInterstitial arg0, Map<Object, Object> arg1) {
//fired when the user completes the action.
}
});

The following callback is sent to the listener:

  • onIncentCompleted: This means that the user has completed the incent action. It also has a map of parameters that the publisher can configure during set up.

Testing the Integration

Set your property in test mode as described here.

Analytics

While configuring the SDK, you have already initialized the InMobi SDK with the appropriate property ID. Continue to use the same property ID with analytics integration. If you have missed this configuration step, InMobi Analytics will not work.

Tracking Installs and Session Events

Tracking Installs

By default, InMobi will report installs upon initializing the SDK. For doing this, you need to set up your campaigns appropriately. Please see here for instructions on how to set up a campaign.

Reporting for this will be available on the user interface. Instructions are available here.

Permissions for Tracking Installs

Mandatory Permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Note: ACCESS_NETWORK_STATE permission is required to check the network state. This will help increase accuracy when reporting installs.

Optional Permissions

Enabling Read logs permission for tracking installs on android versions lower than API 14.

<uses-permission android:name="android.permission.READ_LOGS" />

Setting the Referrer for Tracking Installs

There are two ways in which you can integrate the Google Play referrer for tracking installs:

Using InMobi IMAdTrackerReceiver

This will be used to track installs using the referrer. InMobi recommends this method of integration.

Add the com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver broadcast receiver to your AndroidManifest.xml within the <application> tag. The IMAdTrackerReceiver will be used to track installs using the Google Play referrer.

<receiver
android:name="com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>

Using custom INSTALL_REFERRER broadcast receiver or other Tracking Solutions along with InMobi

If you do not use the referrer for your own use cases, we recommend that you just register the IMAdTrackerReceiver broadcast receiver for intent com.android.vending.INSTALL_REFERRER in the manifest file, and let the SDK collect the referrer automatically. However, if you are using the referrer for your own use cases, or if your application has multiple trackers that require their own broadcast receivers to track INSTALL_REFERRER, implement your own custom receiver. If there is more than one broadcast receiver in the manifest to handle INSTALL_REFERRER intent, only the first receiver receives the intent. Place your custom broadcast receiver in the manifest and inside onReceive of your custom receiver, invoke all the receivers of the trackers, including the InMobi Analytics receiver as well as perform your own referrer processing.INSTALL_REFERRER intent.

Manifest Changes:

<receiver
android:name="com.inmobi.app.kitchensink.MyReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<!-- Only the first receiver(MyReciever) registered in manifest will receive the broadcast. For rest of the tracking receivers call onReceive of the receiver from the first receiver’s(MyReceiver) onReceive --> 
<receiver
android:name="com.inmobi.commons.analytics.androidsdk.IMAdTrackerReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<receiver android:name="com.xyz.tracking..XYZTrackingReceiver" android:exported="true" />
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>

Code Changes:

public class MyReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.android.vending.INSTALL_REFERRER"))
{
// Pass the intent to the IAT receiver using 
new IMAdTrackerReceiver().onReceive(context, intent);
// Pass the intent to other receivers.
new XYZTrackingReceiver().onReceive(context, intent);
// Implement your own referrer processing here
}
}

Advertisers who want to extract their referrer can follow the instructions provided here.

Testing Referrer Integration

Please follow the step-by-step guide to test the referrer integration provided here.

Tracking Session Events

Sessions are auto-tracked for Android versions 4.0 and above (API 14). This can be turned off by following the steps mentioned here. For Android versions 4.0 and below, sessions need to be started and stopped manually. This can be done using the following APIs:

startSession

Evoke startSessionManually when the application is launched. Do this before any other event is recorded, preferably in the onCreate() or onResume life cycle methods of the launcher activity.

InMobiAnalytics.startSessionManually(Context context, Map<String, String> analyticsAttributeMap)
InMobiAnalytics.startSessionManually(Context context)
endSession

Evoke endSessionManually when the app is closed, typically in onDestroy() or onPause().

InMobiAnalytics.endSessionManually(Map<String, String> analyticsAttributeMap)
InMobiAnalytics.endSessionManually()

Tracking Section Events

All the different events should be fired in between the startSessionManually and endSessionManualy API calls.

Note: startSession and stopSession is called automatically for API 14 and above.

BeginSection

Evoke this event when the user has started viewing/playing a new Section. This could be a tab or app content in the case of non-gaming apps, or a level in the case of gaming apps.

InMobiAnalytics.beginSection(String sectionName, Map<String, String> analyticsAttributeMap)
InMobiAnalytics.beginSection(String sectionName)

Example:

InMobiAnalytics.beginSection("Waterworld", null);
InMobiAnalytics.beginSection( "Waterworld");

EndSection

Evoke this event when the user has finished viewing/playing a section.

InMobiAnalytics.endSection(String sectionName, Map<String, String> analyticsAttributeMap)
InMobiAnalytics.endSection(String sectionName)

Example:

InMobiAnalytics.endSection( "Section12", null)
InMobiAnalytics.endSection( "Section12");

Tracking Custom Events

Use tagEvent to record any arbitrary event that is not covered by the above APIs. Use the analyticsAttributeMap to capture instance-specific attributes of the event.

Custom Event

InMobiAnalytics.tagEvent(String eventName, Map<String, String> analyticsAttributeMap)
InMobiAnalytics.tagEvent(String eventName)

Example:

Map<String, String>musicMap = new HashMap<String, String>();
musicMap.put("SongPlaying", "Song2");
musicMap.put("Artist", "Blur");
musicMap.put("Volume", "9");
InMobiAnalytics.tagEvent("Music Muted", musicMap);

Reporting Custom Goals

Custom goals are deprecated in this release; this feature will soon be disabled. We strongly recommend that you use the Custom Events feature, instead.

Custom goals can be reported using reportCustomGoal method in the InMobiAnalytics class.

InMobiAnalytics.reportCustomGoal(String goal)
InMobiAnalytics.reportCustomGoal("mycustomgoal");

Note: InMobi.initialize must be called before calling reportCustomGoal.

Tracking Purchase Events

In-app purchases made via Google Play billing APIs can now be tracked and analyzed using InMobi Analytics. To track purchases, InMobiAnalytics.tagTransactionManually should be called.

  1. Implement Google Play billing version API v3 as per these instructions.
  2. When a user makes a purchase, Google Play is launched. After the purchase, the Google Play app closes and control will come back to the app. In the app, the onActivityResult callback will be received with the purchase intent.
  3. Call the tagTransactionManually API from the onActivityResult and pass the purchase intent. The purchase intent, however, does not have all the details. To track complete details of purchase, we need the virtual goods details too. This can be obtained by calling the Google Play billing API, getSkuDetails(). This will return a bundle with the virtual goods details. Pass the bundle, along with the purchase intent, to the tagTransactionManually API.

Transaction Event

InMobiAnalytics.tagTransactionManually(Intent data, Bundle skuDetails)

Example:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent purchaseData) { 
if (resultCode == RESULT_OK) {
//Get virtual goods details
Bundle querySkus = new Bundle();
//my product list is the arraylisy containing your sku ids
querySkus.putStringArrayList("ITEM_ID_LIST", myProductsList());	
Bundle skuDetails = null;
//mService is the IInAppBillingService instance
skuDetails = mService.getSkuDetails(3, getActivity().getPackageName(), "inapp", querySkus);
//Invoke tagTransaction with purchase intent and skudetail(virtual goods details)
InMobiAnalytics.tagTransactionManually(purchaseData, skuDetails);
} 
}

Tracking User Attributes

Use SetUserAttribute to collect the user attributes like Wallet Size in a game, or Portfolio Value in a Demat account. Self-provided user attributes allow publishers to create more specific segments.

Example: InMobiAnalytics.setUserAttribute(“WalletSize”, “1000000”);

Actions

Actions are the insight-driven campaigns used by developers on particular user segment(s) to increase monetization and engagement levels. Actions allow for the quick setup and launch of campaigns by a specific user (virtual goods sale, reward, cross promote, or display ads).

Interstitial Action

An interstitial action is rendered as a full-screen offer (usually best shown when the app is paused such as “level complete,” “main menu”, and so on) on an interstitial slot. There are separate calls for loading and showing interstitial actions.

You have already initialized the InMobi SDK with the appropriate property ID during configuration. Continue to use the same property ID with the interstitial integration. If you have missed that configuration step, InMobi will fail to load the interstitial actions.

Note: Please contact InMobi to enable your account for actions. For help on creating and configuring slots, please see here.

Actions interstitials behave just like regular interstitials from an integration perspective. Refer to this section to know more about interstitials. The interstitial object needs to be initialized with your slotId as Actions are configured via slots.

Syntax:

IMInterstitial interstitial = new IMInterstitial(activity, YOUR-SLOT-ID);

Example:

IMInterstitial interstitial = new IMInterstitial(activity, 1234567890L);

Using Custom Payload

Custom JSON values can be passed to your app. These values can be configured here. When the user accepts or rejects an action, onInterstitialInteraction will get fired for interstitials.

The map will contain the following data:

Accept

Key

Value

type

action

behavior

accept

data

<YOUR-PARAMS-AS-STRING>

Reject

Key

Value

type

action

behavior

reject

data

<YOUR-PARAMS-AS-STRING>

Example:

IMInterstitial interstitial = new IMInterstitial(this, “YOUR_SLOT_ID”);
interstitial.setIMInterstitialListener(new IMInterstitialListener() {
@Override
public void onShowInterstitialScreen(IMInterstitial arg0) {
}
@Override
public void onLeaveApplication(IMInterstitial arg0) {
}
@Override
public void onInterstitialLoaded(IMInterstitial arg0) {
arg0.show();
}
@Override
public void onInterstitialInteraction(IMInterstitial arg0,
Map<String, String> arg1) {
if(arg1.get("action_type").equals("Interstitial") &&
arg1.get("accepted").equals("true")){
// read data from arg1.get("payload")
}
}
@Override
public void onInterstitialFailed(IMInterstitial arg0, IMErrorCode arg1) {
}
@Override
public void onDismissInterstitialScreen(IMInterstitial arg0) {
}
});
interstitial.loadInterstitial();

Controlling Ad Behavior

Actions currently allow you to control ad behavior by giving a callback response in the onInterstitialFailed() callback:

DO_MONETIZE: Returned when the segment/slot is configured for ads. By default, a segment is configured for ads if either no house actions are targeted, or house actions have reached frequency caps.

DO_NOTHING: Returned when the segment/slot is configured for no ads. This can be done by going to a particular user segment and turning off ads.

Validating Integration with Google Play Services

The InMobi SDK requires validation with Google Play Services to function properly. To do this, follow the steps below:

Testing the Debug Build

  1. Enable the Debug Logging mode on your app.
  2. When the app launches, if the following line is visible in the logcat, your integration is correct.
    Note: The publisher device ID is <<your-device's-Google-Play-ID>>
  3. This ID should be same as the GPID in the phone account settings.

Testing the Release Build

Build the release APK using the ProGuard settings (as mentioned in the config section), and with debug logs enabled. You should see the same logs. If the GPID is correctly printed, the ProGuard settings are correct and your app will work properly.

Advanced Settings

Disabling Hardware Acceleration

In your app, if you observe the ad flickering (a known issue with Android), you can disable hardware acceleration on banner and interstitial objects by using the disableHardwareAcceleration API.

Example:

IMBanner banner = new IMBanner(activity, new IMAdSize(IMBanner.INMOBI_AD_UNIT_320X50));
banner.disableHardwareAcceleration();

Note: The Disable Hardware Acceleration API is not intended to be used with mediation.

Disabling hardware acceleration could cause a bad user-experience if a HTML5 video is played. Disabling this feature is strongly discouraged.

Using ProGuard

Please note that InMobi Android SDK 4.0 is already obfuscated, shrunk, and optimized using ProGuard.

If you are running ProGuard on your Android application, ensure that the following directive is added in your ProGuard configuration file:

-keep class com.inmobi.** { *; }

-dontwarn com.inmobi.**

Debugging the SDK

For general troubleshooting, developers can use the LogLevel property to send InMobi a snapshot of the detailed logs.

InMobi.setLogLevel(LOG_LEVEL.DEBUG);

To check the version of the InMobi Ad Network SDK, use:

InMobi.getReleaseVersion()

Providing Demographics Data

All non-context specific parameters can be passed to InMobi for richer ad targeting. Class InMobi provides static methods to set demographic information about the user. InMobi supports the following parameters:

Gender

Description

Gender of the user

  • Male
  • Female
  • Unknown

Parameter Type

enum GenderType

API

setGender

Valid Values

  • GenderType.MALE
  • GenderType.FEMALE
  • GenderType.UNKNOWN

Examples

InMobi.setGender(GenderType.MALE);

Education

Description

The education level

  • High school, or less
  • College, or graduate
  • Postgraduate, or above
  • Unknown

Parameter Type

enum EducationType

API

setEducation

Valid Values

  • EducationType.HIGHSCHOOLORLESS
  • EducationType.COLLEGEORGRADUATE
  • EducationType.POSTGRADUATEORABOVE
  • EducationType.UNKNOWN

Examples

InMobi.setEducation(EducationType.HIGHSCHOOLORLESS);

Ethnicity

Description

Ethnic group of the user

  • Asian
  • Hispanic
  • Africanamerican
  • Caucasian
  • Other
  • Unknown

Parameter Type

enum EthnicityType

API

setEthnicity

Valid Values

  • EthnicityType.ASIAN
  • EthnicityType.CAUCASIAN
  • EthnicityType.HISPANIC
  • EthnicityType.AFRICANAMERICAN
  • EthnicityType.UNKNOWN
  • EthnicityType.OTHERN

Examples

InMobi.setEthnicity(EthnicityType.ASIAN);

Date of Birth

Description

The date of birth of the user

Parameter Type

Calendar

API

setDateOfBirth

Valid Values

Valid Date

Examples

InMobi.setDateOfBirth(dateOfBirth);

Income

Description

Approximate annual household income (in US Dollars)

Parameter Type

int, to be specified in $

API

setIncome

Valid Values

  • integer
  • greater than zero

Examples

  • // Income in USD: $120,000
  • InMobi.setIncome(50000);

Age

Description

The age of the user

Parameter Type

Integer

API

setAge

Valid Values

  • integer,
  • greater than zero

Examples

InMobi.setAge(24);

Postal Code

Description

The postal code (Usually a 5 digit number).

Parameter Type

String

API

setPostalCode

Valid Values

”12345” - Please enter appropriate postal code, as applicable

Examples

InMobi.setPostalCode("98765");

Area Code

Description

The area code (part of the telephone number).

Parameter Type

String

API

setAreaCode

Valid Values

”123” - Please enter appropriate area code, as applicable.

Examples

InMobi.setAreaCode(“123”);

Interests

Description

Any additional relevant description of the user, or their preferences, separated by commas. Valid acceptable values are mentioned below.

Parameter Type

String

API

setInterests

Valid Values

  • Business
  • Tech
  • Travel
  • Shopping
  • Entertainment
  • Fashion
  • Fitness
  • Foodie
  • Gamer
  • Jobs
  • Sports

Examples

InMobi.setInterests("Jobs");

ID Type

Description

Indicates a login ID and session ID in the publisher's domain

  • Login ID
  • Session ID

Parameter Type

enum IMIdType, String value

API

addIDType or removeIDType

Valid Values

  • IMIDType.ID_LOGIN
  • IMIDType.ID_SESSION

Examples

  • InMobi.addIDType(IMIDType.ID_LOGIN, "John.doe@facebook.com");

  • InMobi.addIDType(IMIDType.ID_SESSION, "john.doe@gmail.com");

Sexual Orientation

Description

The sexual orientation of the user (if available)

  • Straight
  • Bisexual
  • Gay
  • Unknown

Parameter Type

enum SexualOrientation

API

setSexualOrientation

Valid Values

  • ”straight”,
  • ”bisexual”,
  • ”gay”,
  • ”unknown”.

Examples

InMobi.setSexualOrientation("SexualOrientation.STRAIGHT");

Marital Status

Description

The martial status of the user

  • Single
  • Divorced
  • Engaged
  • Relationship

Parameter Type

enum MaritalStatus

API

setMaritalStatus

Valid Values

  • “single”
  • “divorced”
  • “engaged”
  • “relationship”

Examples

InMobi.setMaritalStatus("MaritalStatus.SINGLE);

Language

Description

The native language of the user (if known)

Parameter Type

String

API

setLanguage

Valid Values

”ang” - Values are expected in 3 letter codes from ISO 639-2/5.

See here for details.

Examples

InMobi.setLanguage("ang");

Has Children

Description

Whether the user has children

Parameter Type

enum HasChildren

API

setHasChildren

Valid Values

  • ”True”
  • ”False”
  • ”Unknown”

Examples

InMobi.setHasChildren("Haschildren.true");

FAQs

I have included the Google Play Services Jar in my project. Is that okay?

Google requires the Google Play Services to be included as a dependency project, and not as a Jar. For more details, please refer to setting up Google Play Services.

How do I include Google Play Services in my app?

Google Play services must be added as a library project. Details on how to include this are in the Google Play Services documentation.

Important:

  • Google Play Services must NOT be included as a pre-compiled Jar, but as a project dependency in Eclipse or Android Studio.
  • Ensure that the meta tag required to reference the Google Play Services Jar is present in the project manifest file

I have an older version of the Google Play Services included. Do I need to update?

Google Play Services older than version 4.0 do not support the advertising ID. You must include a newer version of the Google Play Services Library.

My project does not compile because of an error in the Manifest file. The error is in the meta tag I added to reference Google Play Services. How do I make the error go away?

Do not create an integer.xml file in your res folder. This error will not occur if the Google Play Services is added as a library project.

My project compiles but I see an error related to Google Play Services in my IDE console. How do I fix it?

If you see an error like the below in the integration, please do not ignore it. Check the integration.

E/GooglePlayServicesUtil(29708): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

This error above indicates that the required meta tag in the Manifest file (needed to reference the Google Play Services SDK) was not included. Please include the tag in your project's manifest file. You must also make sure that the Google Play Services SDK version is not hardcoded in this tag, but is instead referenced from the original Google Play Services project.

I use ProGuard with my project. Are there any precautions I need to take?

Yes, you need to modify your ProGuard configuration to filter out Google Play Service classes from obfuscation. You must add the ProGuard configs that are required by Google This is required as the InMobi SDK accesses these classes through reflection and ProGuard-ing them prevents access.

Was this page helpful?

On This Page