android-guidelines | Native Ads

InMobi Native ads seamlessly blend in with your app’s content, maximizing user engagement without compromising on user experience. You can choose and customize the layout that best matches the design of your app. It is ideal for news, utility and communication apps.

InMobi Native Ads can have video and/or static image both. Depending on the placement you can opt for:

  • In-Feed Ad - a muted autoplay HD video or a simple static image ad.
  • Splash Ad - blends in the launch screen of apps and monetize user time when the app is loading in the background. These ads can also be a muted autoplay HD video ad or a simple static image ad.

Static Feed Ad

InFeed Video Ad

Splash Video Ad

Follow these simple steps and start monetizing with Native ads:

Setting up a Native Ad Placement

  1. Create a Native Content placement.

  2. In-Feed Video Ad Placement
    1. Select FEED as the Native Ad Layout.

    2. For In-Feed Video, select either of the aspect ratio 256:135 or 16:9. Both the aspect ratios will have default static native fallback enabled with similar aspect ratio.

  3. Static Feed Ad Placement
    1. Select FEED as the Native Ad Layout.

    2. In the integration code, please ensure nativeAd.getPrimaryViewOfWidth(context,convertView, parent, width);Specify width = 25 while fetching your primaryView. It will just show the AdChoices icon and fire the ad render events.
  4. Splash Video Ad Placement
    • Select SPLASH as the Native Ad Layout.

    • Select the desired aspect ratio. Default value for the aspect ratio will be 9:16.

  5. Others (China only):
    • Select Others as the Native Ad Layout.

    • Select aspect ratio 16:9. This will have default static native fallback enabled with similar aspect ratio.
    • A new sub field is added in Others layout called Native Layout Type. It has the following values: “Native Interstitial”, “Native Page”, “Native Banner”, “Native Focus”, “Native Lock Screen”, “Native Other”.
    • Default value will be Native Interstitial in Native layout type field.

  6. Pre-roll Ad Placement
    • Select Pre-roll as the Native Ad Layout.

    • Save the Pre-roll native placement layout.

Adding a Native Ad to Your App

Creating a Native Ad

To create a native ad, create an InMobiNative instance:

public class NativeAdsActivity extends Activity {
……………………
private final List<InMobiNative> mNativeAds = new ArrayList<>();
……………………
InMobiNative nativeAd = new InMobiNative(NativeAdsActivity.this, YOUR_PLACEMENT_ID, nativeAdEventListener);
nativeAd.load();
mNativeAds.add(nativeAd);
……………………
	

Here nativeAdEventListener is an implementation of the NativeAdEventListener abstract class. It is mandatory to supply an implementation of this interface to create a native ad.

Mandatory: You must supply a Context implementation to the InMobiNative constructor. Please make sure your implementation holds a strong reference of InMobiNative otherwise you will not be able to get any callback from SDK for this reference. This can be achieved by making it a member variable of a class or storing it in collection, which lives through your application life cycle.

  • inMobiNative should always be strong reference otherwise you may not receive any callback (load success, load failure etc.) for this reference.
  • If inMobiNative is referenced by any variable please ensure that it is a strong reference.
  • Use android profiler to ensure that inMobiNative is not removed due to garbage collection.

NativeAdEventListener abstract class allows you to listen to key lifecycle events for a native ad.

/**
* A listener for receiving notifications during the lifecycle of a Native ad.
*/
public abstract class NativeAdEventListener {
   /**
    * Called to notify that a native ad was successfully loaded.
    *
    * @param ad Represents the {@link InMobiNative} ad which was loaded
    */
   public void onAdLoadSucceeded(InMobiNative ad) {}
   /**
    * Called to notify that a native ad failed to load.
    *
    * @param ad  Represents the {@link InMobiNative} ad which failed to load
    * @param requestStatus Represents the {@link InMobiAdRequestStatus} status containing error reason
    */
   public void onAdLoadFailed(InMobiNative ad, InMobiAdRequestStatus requestStatus) {}
   /**
    *
    * @param ad  Represents the {@link InMobiNative} ad whose fullscreen was dismissed
    */
   public void onAdFullScreenDismissed(InMobiNative ad) {}
   /**
    * Called to notify that the ad will open an overlay that covers the screen.
    *
    * @param ad Represents the {@link InMobiNative} ad which will go fullscreen
    */
   public void onAdFullScreenWillDisplay(InMobiNative ad) {}
   /**
    * Called to notify that the ad opened an overlay that covers the screen.
    *
    * @param ad Represents the {@link InMobiNative} ad whose fullscreen will be displayed
    */
   public void onAdFullScreenDisplayed(InMobiNative ad) {}
   /**
    * Called to notify that the user is about to leave the application as a result of interacting with it.
    *
    * @param ad Represents the {@link InMobiNative} ad
    */
   public void onUserWillLeaveApplication(InMobiNative ad) {}
   /**
    * Called to notify impression has been recorded for this ad. <b>Note:</b>Override this method to notify
    * viewable impression to the Mediation Adapter.
    *
    * @param ad Represents the {@link InMobiNative} ad for which impression is recorded.
    */
   public void onAdImpressed(InMobiNative ad) {}
   /**
    * Called to notify ad was clicked. <b>Note:</b>Override this method to notify click to the Mediation Adapter.
    *
    * @param ad Represents the {@link InMobiNative} ad which was clicked
    */
   public void onAdClicked(InMobiNative ad) {}
   /**
    * Called to notify that the ad status has changed.
    *
    * @param nativeAd Represents the {@link InMobiNative} ad
    */
   public void onAdStatusChanged(InMobiNative nativeAd) {}
}
	

VideoEventListener abstract class allows you to listen to video lifecycle events for a native ad.

/**
* A listener for receiving notifications during the lifecycle of a Native ad.
*/
public abstract class VideoEventListener {
   /**
    * Called to notify that the video has finished playing.
    *
    * @param ad Represents the {@link InMobiNative} ad
    */
   public void onVideoCompleted(InMobiNative ad) {
   }
   /**
    * Called to notify that the user has skipped video play.
    *
    * @param ad Represents the {@link InMobiNative} ad
    */
   public void onVideoSkipped(InMobiNative ad) {
   }
   /**
    * Called to notify when media audio state changes.
    *
    * @param isMuted Represents whether media is muted or not.
    */
   public void onAudioStateChanged(InMobiNative inMobiNative, boolean isMuted) {
   }
}
	


Loading a Native Ad

To request for a native ad, call the load() method on the InMobiNative instance you created above:

nativeAd.load();
	

The NativeAdListener interface notifies you the result of the ad request. If the ad request was successful, the onAdLoadSucceeded(InMobiNative) event will be generated. If the onAdLoadFailed event is generated, the reason is indicated by the InMobiAdRequestStatus object passed in this event.


Listening to video events

To receive video events register videoEventListener using method setVideoEventListener (VideoEventListener videoEventListener) on the InMobiNative instance you created above:

nativeAd.setVideoEventListener (videoEventListener);
	

The VideoEventListener abstract class notifies you about video events for native ads.


Native Ad APIs

Following are the important APIs in InMobiNative that will help to stitch the ads:

  • View getPrimaryViewOfWidth(context, convertView, parent, width) - Returns a View of specified width (specified in actual pixels). This is the main ad content in your native ad. It will return a view of the same aspect ratio that you selected on the InMobi dashboard while creating the native placement. All impression render events are also fired automatically when this primary view is displayed on the screen.

    If you have selected Feed Layout while creating your placement, specify width = 25 while fetching your primaryView. It will just show the AdChoices icon and fire the ad render events.

    getPrimaryViewOfWidth(..) takes in four parameters:

    • context - The context in which ad is going to be rendered.
    • convertView - This is the complete view of a row of the ListView. You should not provide this as NULL because we use this parameter to recycle our ads effectively. This will allow for a smooth scroll performance.
    • parentView - This is the parent view inside which you will place the primaryView (which is returned by getPrimaryViewOfWidth() function). We need it for determining the layout parameters of Primary View.
    • adViewWidthInPixels - This is the width (in pixels) that you want the primaryView to take up.
  • String getAdTitle() - returns the string title for the ad.
  • String getAdDescription() - returns the string description for the ad.
  • String getAdIconUrl() - returns icon Image String URL for the ad.
  • String getAdCtaText() - returns Click to action string for the ad.
  • String getAdRating() - returns rating for the ad (optional).
  • String getAdLandingPageUrl() - returns landing URL for the ad.
  • boolean isAppDownload - returns true when the featured ad is from an app install advertiser.
  • boolean isReady() - True means the ad is ready to be displayed.
  • void reportAdClickAndOpenLandingPage() - This function fires the click events and opens the landing page. You need not open landing page on your own while using this function.
  • JSONObject getCustomAdContent() - This function returns the JSONObject. This json have additional information (description, image URL, etc.), which can be used to create custom UI around the primary view of the ad.


Stitching a Native Ad

A native ad can be stitched in your app in three formats:

  • In-Feed ads
  • Splash ads
  • Pre-Roll ads

InFeed Ad Integration
  1. Declare an ad position in your feed where you want to show ad.

    For example, to show ad at 4th position:

    private static final int AD_POSITION = 4;
    		
  2. If the ad load is successful, you will get a callback onAdLoadSucceeded(InMobiNative).You should then add the InMobiNativeAd object to your data source within this listener. If your feed in the app is a ListView, a sample implementation for ListView is shown below:
    @Override
           public void onAdLoadSucceeded(@NonNull InMobiNative nativeAd) {
    		AdFeedItem nativeAdFeedItem = new AdFeedItem(nativeAd);
    		mFeedItems.add(AD_POSITION, nativeAdFeedItem);
    		mFeedAdapter.notifyDataSetChanged();
           }
    		

    In the step above, AdFeedItem is an extension class of your FeedItem class, where FeedItem is the class which powers each row of your ListView. Also mItems is the ArrayList, which powers the Adapter of this ListView.

  3. So far, we have loaded an ad and added it to your data source. Now, it’s time to display the ad. The sample implementation for ListView is as follows:
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       final int itemViewType = getItemViewType(position);
       if (itemViewType == VIEW_TYPE_CONTENT_FEED) {
    		//Your app code
       } else {
    	//Since this content type is InMobi Ad, you need to get native Ad view		
           final InMobiNative nativeAd = ((AdFeedItem) feedItem).mNativeAd;
    	View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, parent.getWidth());
    		       if(convertView==null){
              convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
           }
                            ((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
          ((TextView)convertView.findViewById(R.id.title)).setText(nativeAd.getTitle());
          ((TextView)convertView.findViewById(R.id.desc)).setText(nativeAd.getDescription());
          ((TextView)convertView.findViewById(R.id.cta)).setText(nativeAd.getCtaText());
           return convertView;
       }
    }
    		

    The function getItemViewType(position) checks whether the content type is FEED OR AD as given below:

    @Override
    public int getItemViewType(int position) {
       FeedItem feedItem = getItem(position);
       if (feedItem instanceof AdFeedItem) {
           return VIEW_TYPE_INMOBI_STRAND;
       }
       return VIEW_TYPE_CONTENT_FEED;
    }
    		

    We have used some of the APIs described in the section above to show the title, description, and CTA text of the ad. Similarly, the other APIs can be used to show the corresponding parts of the ad.


Splash Integration

Splash experience can be implemented using the same InMobiNative class. However, there are a few things to be noted:

  • You should use InMobiNativeAd.isReady() function to determine if the ad is ready to be shown. Sometimes, your main thread may be occupied and hence you may not receive onAdLoadSucceeded in time. Hence, it is better to proactively check if the ad is ready just after your cut-off time has elapsed.
  • IMPORTANT: You should NOT destroy or refresh the ad if the second screen of the ad is in display. You can check this in the onAdFullScreenDisplayed and not dismiss the ad if this callback is fired.

Sample implementation is as follows:

@Override
public void onAdFullScreenDisplayed(InMobiNative nativeAd) {
	isSecondScreenDisplayed = YES;
}
public void dismissAd() {
   if(isSecondScreenDisplayed){
       Log.d(TAG, "DO NOT DISMISS THE AD WHILE THE SCREEN IS BEING DISPLAYED");
   }
   else
   {
	splashAdView.setVisibility(View.GONE);
	nativeAd.destroy();
   }
}
	

Pre-Roll Integration

Pre-Roll Video experience can be implemented using the same InMobiNative Class. You need to register videoEventListener and need to dismiss the ad view in the following callback:

@Override
public void onVideoCompleted(@NonNull InMobiNative nativeAd) {
	Log.d(TAG, "Media playback complete " + mPosition);
}
	

The Pre-Roll ad can be dismissed as follows:

public void dismissAd() {
	splashAdView.setVisibility(View.GONE);
	nativeAd.destroy();
}
	


Refreshing the Native Ad

You will need to refresh the ad at various points to optimize ad exposure to your users. To refresh the ad, you will need to call the following functions in the exact order.

Note: It is important to remove the adFeedItem object from your data source and destroying it before refreshing. You will then need to create a new object and call load as shown in the following code:

private void refreshAd() {
       Iterator<FeedItems> feedItemIterator = mFeedItems.iterator();
       while (feedItemIterator.hasNext()) {
           final FeedItem feedItem = feedItemIterator.next();
           if (feedItem instanceof AdFeedItem) {
               feedItemIterator.remove();
           }
       }
       // refresh feed
       mFeedAdapter.notifyDataSetChanged();
       // destroy InMobiNative object
       inMobiNativeAd.destroy();
       // create InMobiNative object again
	InMobiNative inMobiNativeAd = new InMobiNative(
	<<Activity Instance>>,
	<<Your Placement ID>>,
	<<InMobiNativeAdListener created in step 1>>);
	inMobiNativeAd.load();
}
	


Managing the InMobiNative Instances

  1. Every instance of InMobiNative represents exactly one ad.
  2. If you want to place ad at multiple positions within a content feed, create as many instances of InMobiNative as the number of ad positions.
  3. You should create instances of InMobiNative in onCreate() callback of Activity or in onActivityCreated() callback of Fragment.
  4. You should destroy the InMobiNative instances in onDestroy() callback of Activity or in OnDestroyView() callback of Fragment.
  5. An InMobiNativeAd object must always be destroyed once you remove it from the data source. All user interactions with the ad view will not be honored after InMobiNativeAd is destroyed. So, you will have to definitely discard the ad view before destroying the InMobiNativeAd.
  6. All InMobiNativeAd instances must also be destroyed, when the component hosting them (your activity in this case) is getting destroyed using the destroy() API.


Click Tracking on the Ad Views

To have the InMobi SDK open the landing URL in addition to reporting a click, call the reportAdClickAndOpenLandingPage() method on the native ad instance:

nativeAd.reportAdClickAndOpenLandingPage();
	

Downloader Integration (If you want to monetize China traffic)

Introduction

In China, due to absence of Google Play, we support direct downloading of APKs through a tool called InMobi Downloader. This feature is available only in the China version of InMobi Android SDK. The InMobi Downloader manages the advertiser app download and installation. It communicates events to the advertisers to enable attribution while providing a bespoke experience for publishers and users.

Changing the Manifest File

You need to add a new service to manifest file as follows:

<service
	android:name="com.inmobi.ads.ApkDownloader$ApkDownloadService"
	android:enabled="true">
</service>
	

The downloader requires the permission to write external storage as follows:

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

Android 7 (Nougat and above)

New changes are required from Android N onwards, since the design for file sharing has changed. Other applications cannot access the files of your app, and hence we will need the PackageInstaller app to install the APK file downloaded by us. Reference here.

  • Add res/xml/provider.xml
    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
       <external-path name="external_files" path="."/>
    </paths>
    		
  • In AndroidManifest.xml, add the following:
    <provider
       android:name="android.support.v4.content.FileProvider"
       android:authorities="{appPackageName}.fileprovider"
       android:exported="false"
       android:grantUriPermissions="true">
       <meta-data
           android:name="android.support.FILE_PROVIDER_PATHS"
           android:resource="@xml/provider" />
    </provider>
    		
  • For Android Oreo (8 and above), add the following in AndroidManifest.xml:
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    		

Invoking InMobi Downloader

You need to enable downloader while creating your InMobi native ad object as follows:

@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	InMobiNative nativeAd = new InMobiNative(
	<<Activity Instance>>,
	<<Your Placement ID>>,
	<<InMobiNativeAdListener>>);
	nativeAd.setDownloaderEnabled(true);
	nativeAd.load();
	//Your App code here
}
	

Getting Downloader Callbacks

The InMobi Downloader provides callbacks in the listener method named onAdStatusChanged(). This will be fired every time the downloader changes its state. The status can be accessed through getDownloadStatus() method. The possible states and their corresponding status messages are:

STATE_UNINITIALIZED = -2;
STATE_INITIALIZING = -1;
STATE_DOWNLOADING = 0;
STATE_DOWNLOADED = 1;
STATE_ERROR = 2;
	

During the state when the downloader is downloading the APK ( STATE_DOWNLOADING = 0), you can access the progress of download using getDownloadProgress() method. You can use this progress to show a progress bar to your users.

Note: Do note that onAdStatusChanged() is fired every time the download percentage changes within the state STATE_DOWNLOADING = 0. A sample implementation of this is shown below:

public void onAdStatusChanged(@NonNull InMobiNative nativeAd) {
	Log.d("InMobi Downloader status is", "value: " + nativeAd.getDownloader().getDownloadStatus());
	if (nativeAd.getDownloader().getDownloadStatus() == InMobiNative.Downloader.STATE_DOWNLOADING) {
	progressBar.setProgress(nativeAd.getDownloader().getDownloadProgress());
	}  
}
	

Implementing Backfill

InMobi's SDK can run both HTML and native units against your native placement. You can run the following ad sizes depending on the real-estate reserved for your native placement.

  • 320x50 HTML Banner
  • 300x250 HTML Banner
  • 320x480 HTML Full screen Banner
  • 320x568 HTML Full screen Banner
To switch this on, you need to reach out to your respective partner manager with the preferred backfill size. Also, you will need to handle this in your code as follows:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
   final int itemViewType = getItemViewType(position);
   if (itemViewType == VIEW_TYPE_CONTENT_FEED) {
		//Your app code
 	} 
   else {
   		//Since this content type is InMobi Ad, you need to get native Ad view
		final InMobiNative nativeAd = ((AdFeedItem) feedItem).mNativeAd;
		//Detect whether its a backfill response or normal native
		JSONObject customContent = currentNativeAd.getCustomAdContent();
                boolean isBackFillBanner = false;
                try {
                    isBackFillBanner = customContent.getBoolean("isHTMLResponse");
                } catch (JSONException e) {
                    isBackFillBanner = false;
                }
		if(isBackFillBanner){	
			View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, Math.round(getResources().getDisplayMetrics().density*250));
 		   	if(convertView==null){
 	         		convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
 	       		}
			((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
			return convertView;
		} 
		else {
		 	View primaryView = nativeAd.getPrimaryViewOfWidth(context, convertView, parent, parent.getWidth());
		   	if(convertView==null){
	         		 convertView = mLayoutInflater.inflate(R.layout.ad_item, parent, false);
	       		}
		  	((RelativeLayout)convertView.findViewById(R.id.primaryView)).addView(primaryView);
		   	((TextView)convertView.findViewById(R.id.title)).setText(nativeAd.getTitle());
		   	((TextView)convertView.findViewById(R.id.desc)).setText(nativeAd.getDescription());
		   	((TextView)convertView.findViewById(R.id.cta)).setText(nativeAd.getCtaText());
		  	 return convertView;
   		}
	}
}
	

Note:

  • To detect if the response is backfill, the customAdContent will contain the string isHTMLResponse.
  • Do NOT scale the width of the HTML banner response. For e.g. if you selected backfill of 300x250, make sure the provided width is hardcoded 250.
  • Do NOT add the CTA button in case of backfill response. The clicks will not be monetized in case you add this button alongside the ad.

Retrieving CreativeID

At times, there are rogue advertisers who escape all the ad quality checks and end up compromising the user experience on the app by showcasing either an irrelevant, distasteful or disrupting creative to the user. To combat such situations, you can retrieve the creativeID of the ad instance and report back to your InMobi point of contact with the encrypted creativeID.

mNativeAd.getCreativeId()// mNativeAd is an example instance.

Testing the Integration

  1. Configure the test mode on InMobi portal.

    Go to Tools - Diagnostics and switch Test Mode to either Global ON or Selective ON.

    If you are integrating an ad unit for the first time Set Test Mode to Global ON.
    If you want to selectively turn on test traffic for a set of devices·

    You already have a prior version of the SDK integrated for this particular ad unit and therefore you should restrict your testing to only few devices
    Set Test Mode to Selective ON.

    In the device section:

    1. In the Device ID box, type the device ID.
    2. In the Device Name box, set any name.
    3. Click Add Device to add the test device.

    If you already have a device configured, you can select the device and test mode would be enabled.

    Note: You MUST turn off the test mode before going live or else your app will fail to monetize.

    Now you are all set to get test ads.

    Getting the Device ID

    The device id is the Google Play Advertising ID (GPID). To get the device ID, configure the SDK to print debug logs to the console. You can do so by adding the following line to your Activity where you are integrating Native ads.

       InMobiSdk.setLogLevel(LogLevel.DEBUG);
    		

    The device ID will now be printed in debug logs in the DDMS console like so:

  2. You will also get feedback on the diagnostics tab on the ad unit and ad request and this can be particularly helpful during integration.

Helpful Debug Information

Once you have enabled debug logs as mentioned in step 1, SDK will print key logs to the DDMS console that provide useful information about the initialization and ad load lifecycle.

The following table captures these logs.

SDK Initialization

Scenario Log Level Log Message
Publisher passed null or empty account id Error Account id cannot be null or empty. Please provide a valid Account id.
Publisher passed a valid account id Debug InMobi SDK initialized with account id: <account id>
Publisher passed an invalid account Id Error Invalid account id passed to init. Please provide a valid account id.
Publisher didn't grant the mandatory permissions Debug Please grant the mandatory permissions : INTERNET & ACCESS_NETWORK_STATE, SDK could not be initialized.
Permissions granted to the SDK Debug Permissions granted to the SDK are : <List of permissions granted>
Newer version of SDK is available Debug A newer version (ver. 6.0.0) of the InMobi SDK is available! You are currently on an older version (ver. 5.3.1). Download the latest InMobi SDK from http://www.inmobi.com/products/sdk/#downloads

Common Ad Lifecycle Messages

Scenario Log Level Log Message
Ad requested when no network available Error Network not reachable currently. Please try again.
Ad requested when ad state is loading or available Error An ad load is already in progress. Please wait for the load to complete before requesting for another ad (Placement id : <placement id> ).
Publisher device Id Debug Publisher device id is <Device Id>

Messages for Native Ad Integrations

Scenario Log Level Log Message
Publisher supplied a null context Error Unable to create InMobiNative ad with null Activity object
Publisher created a native ad without initializing the SDK Error Please initialize the SDK before creating a Native ad
Publisher created a native ad with an invalid placement id Error NA
Publisher supplies a null InMobiNativeAdListenerobject Error Listener supplied is null,the Native Ad cannot be created
Publisher called load on a native Debug Fetching a Native ad for placement id: <placement id>
Ad is successfully fetched from server Debug Native ad successfully fetched for placement id: <placement id>
Failed to fetch the ad Error Failed to fetch Native ad for placement id : <Placement id> with error : <Status code / message>
When AdView is inflated Debug Ad markup loaded into the container will be inflated into a View

Advanced

Lock Screen Ads

For lock screen integration, you may want to prefetch ads and not tie them to any specific activity. The InMobi SDK allows you to create native ad units that can be maintained in your Application subclass. Your app can then use the native ad unit in your lock screen Activity where the monetization event will occur.

  • Prefetch native ads: create an InMobiAdRequest to supply specific targeting information to the ad server.
  • Call InMobiNative.requestAd(Context, InMobiAdRequest, NativeAdRequestListener) by supplying an implementation for the NativeAdRequestListener interface as mentioned below:
    public class YourApplication extends Application {
        ... 
        private InMobiAdRequest mInMobiAdRequest;
        private NativeAdRequestListener mListener;
        Private InMobiNative mNativeAd;
        ...
        public void onCreate() {
            mInMobiAdRequest = new InMobiAdRequest.Builder(PlacementId.YOUR_PLACEMENT_ID)
                    .build();
            mListener = new InMobiNative.NativeAdRequestListener() {
                @Override
                public void onAdRequestCompleted(InMobiAdRequestStatus status, InMobiNative nativeAd) {
                    if (status.getStatusCode() == NO_ERROR && nativeAd != null) {
                        mNativeAd = nativeAd;
                    } 
                }
            };
            InMobiNative.requestAd(this, mInMobiAdRequest, mListener);
            ...
        }
        public InMobiNative getNativeAd() {
            return mNativeAd;
        }
    }
    		
  • In your Activity, you can then get an instance of this ad unit by calling the getNativeAd() method on your Application subclass.

    Register this native instance for lockscreen actions using showOnLockScreen(LockScreenListener lockScreenListener). This listener will be invoked as soon as user interacts with ad and lock screen needs to be dismissed to complete this interaction.

    * This method should be called before load(Context) or load().

  • Load the ad markup by calling load(Context), and supply your Activity where the monetization event will occur.
  • Post ad load, request for ad assets by call getAdContent() to fetch assets.
    takeAction()

    Call this method to take action which is caused by any user interaction with ad view on Lockscreen. This interaction will be reported by com.inmobi.ads.InMobiNative.LockScreenListener#onActionRequired(InMobiNative). This method should be called by app after android.content.Intent.ACTION_USER_PRESENT broadcast.