Develop ads for the Google Mobile Ads SDK

Use the Google Mobile Ads SDK

In order to use the Google Mobile Ads SDK, you must gather the App ID, ad unit IDs, and ad sizes for your developer.

Find the Google Mobile Ads Application IDs

  1. Sign in to Google Ad Manager.
  2. Click Inventory and then Mobile apps.
  3. Find the mobile app for which you need the ID, or claim a new mobile app.
  4. Click Click to copy to copy the "App ID" to your clipboard. Send this information to your developer.

Find ad unit IDs and sizes

  1. Click Inventory and then Ad units.
  2. Click the name of the ad unit for which you want to create an ad tag, or create a new ad unit.
  3. Click Tags.
  4. Select the tag type "Mobile Application Tag" and click Continue.
  5. From "Tag results", copy the "Ad unit ID" and "Ad unit sizes". Send this information to your developer.

Additional JavaScript functions

To take advantage of the functionality of the Google Mobile Ads SDK, refer to the developer documentation. Here are some highlighted functions for modifying the <head> section of the creative.

Access to device capabilities

The SDK exposes the capabilities of the in-app browsers available on iOS and Android. This allows developers to access device capabilities such as the accelerometer, gyroscope and compass via HTML5 where the platform supports them. Please refer to the documentation for Android and iOS for more information on these capabilities.

App events

App events enable you to execute custom code in your application when a creative dispatches an app event. With app events, you can introduce custom ad executions that interact with the application, such as changing the background color of the app.

Learn how to implement app events.

Scaling image to full screen

If you find that your full screen ad is only taking up part of the screen, insert the following code in the <head> section of the creative:

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>.

Sample code for in-app: Mobile Click To Calendar using MRAID v2.0

This template is a banner ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then their default calendar application will create a new event with their consent.

Behavior and UI elements

The creative comprises the following UI elements:

  • The banner image and its height + width.
  • Information about the event is required such as the summary, description, location, start date and end date.
Name Type Required Description
Banner Image File File Yes Image of the banner ad.
Banner Image Width Number Yes Width of the Banner Image.
Banner Image Height Number Yes Height of the Banner Image.
Event Summary Text Yes Summary of the event.
Event Description Text Yes Description of the event.
Event Location Text No Location of the event.
Event Start date Text Yes The start date of the event. The start date should take the following form: '2016-10-22T00:00-05:00'. For example this is 22nd October 2016 from 0:00 to 05:00.
Event End date Text Yes The end date of the event. The end date should take the following form: '2016-10-22T00:00-05:00'. For example this is 22nd October 2016 from 0:00 to 05:00.
 

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a href="#" onClick="addToCalendar()"; return false;>
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" />
</a>
</div>
<script>

// Check whether mraid is ready by adding event listener
function doReadyCheck(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  }else{
    showMyAd();
  }
}

// Once mraid is ready, it does not need to listen to the ready event anymore
function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

// Only show Ad when mraid is ready
function showMyAd(){
  var advertElement = document.getElementById("normal");
  advertElement.style.display = 'block';
}

// Add event to the calendar using appropriate input if the device supports calendar manipulation
function addToCalendar(){

  // Register the click by creating an image
  var x = document.createElement("IMG");
  x.setAttribute("src", "%%CLICK_URL_ESC%%");
  window.top.document.body.appendChild(x);

  if(mraid.getVersion()=="2.0"){
    mraid.createCalendarEvent({summary: "[%EventSummary%]", description: "[%EventDescription%]", location: "[%EventLocation%]", start: "[%EventStartDate%]", end: "[%EventEndDate%]"}); 
  } 
  return false;
}

doReadyCheck();
</script>
</body>
</html>

Test adunit name: ali_Calendar

Sample code for display: Expandable Footer Template using MRAID v2.0

This template is a two-component ad unit that starts off as a bottom screen banner. If a user clicks on the banner, then the ad will resize to some specific dimensions. If the bigger ad is clicked on, then the user is redirected to a specific website.

The width can either be the size of the banner or take up the whole width of the screen (if the value of FullWidthResize is "Yes").

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets (for each of these assets, the file, height and width are required)
    • Banner Image component
    • Resized Banner component
    • Close button icon
  • Can adjust the position of the close button so that it is either on the top right or top left of the screen.
  • Can change the background color of the ad.
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background colour of the space occupied by the resized image and of the space occupied by the banner.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Resized Image File File Yes The image that will be displayed when the banner has been clicked on.
Resized Image Height Number Yes The height of the resized image.
Resized Image Width Number Yes The width of the resized image.
Close Icon File Yes The image file for the “close” button.
Close Icon Width Number Yes The width of the “close” button. (30 is the average width).
Close Icon Height Number Yes The height of the “close” button. (30 is the average height).
Position Of Close Button List No Can position the “close” button so that it is on the top right or top left of the screen. Possible values are “Right” or “Left”. If this is left blank, then it will position the close button to the top right of the screen.
Full Width Resize List No Can make the resized ad take up the entire width of the screen if the value is “Yes”. If the value is “No”, then the width will be the same size as the original banner. Possible values are “Yes” and “No”, the default is “No”.
 

<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
<style>
#close_button {
  position: absolute;
  top: 4px;
  right: 4px;
  display:block;
}

#resized img {
  display : block;
  margin : auto;
}
</style>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a onClick="resize();">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]"  />
</a>
</div>

<div id="resized" style="display:none; top:0px;">
<a onClick="openURL()">
<img width="[%ResizedImageWidth%]"  height="[%ResizedImageHeight%]" src="[%ResizedImageFile%]"/>
</a>
<div id="close_button">
<img width="[%CloseIconWidth%]" height="[%CloseIconHeight%]" src="[%CloseIcon%]"/> 
</div>
</div>

<script>
<!--
// Variables
var closeButton = document.getElementById("close_button");
var bodyElement = document.body;
var advertElement = document.getElementById("normal");
var resizedElement = document.getElementById("resized");
var resizeBannerWidth;

function changeBodyElementStyle() {
  // Change background color
  if ("[%ResizedBackgroundColor%]") {
    bodyElement.style.backgroundColor = "[%ResizedBackgroundColor%]";
    resizedElement.style.backgroundColor = "[%ResizedBackgroundColor%]";	
  }
}

function openURL() {
  mraid.open("%%CLICK_URL_ESC%%[%ClickThroughURL%]");
}

//Check whether MRAID is ready by adding event listener
function checkIfReady(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  } else{
    showMyAd();
  }
}

function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

// Set resizing properties and resize
function resize(){
	// If FullWidthResize is "Yes", then the resized advert takes up the whole width. Otherwise takes up the width of the original banner
	if ("[%FullWidthResize%]" == "Yes") {
	    resizeBannerWidth = screen.width;
	} else {
	    resizeBannerWidth = mraid.getDefaultPosition().width;
	}	
	
  if(mraid.getVersion()=="2.0"){
    if ("[%PositionOfCloseButton%]" === "Left") {
	  closeButton.style.left = "0";

mraid.setResizeProperties({"width":""+resizeBannerWidth+"","height":"[%ResizedImageHeight%]","offsetX":"","offsetY":"","customClosePosition":"top-left", "allowOffscreen":false});
	} else {
	  closeButton.style.right = "0";

mraid.setResizeProperties({"width":""+resizeBannerWidth+"","height":"[%ResizedImageHeight%]","offsetX":"","offsetY":"","customClosePosition":"top-right", "allowOffscreen":false});
	}
    mraid.resize();
	return false;
  }
  else{
    return true;
  }
}

// Displays the advert and add an event listener to it to detect whether to resize
function showMyAd(){
  advertElement.style.display = "inline";
  mraid.addEventListener("stateChange",updateAd); 
}

// updateAd is called when MRAID changes state - calls toggleLayer to expand/ reduce ad size
function updateAd(state){
  if (state == "resized"){
    toggleLayer('normal', 'resized');
  }else if(state == "default"){
    toggleLayer('resized', 'normal');
  }
}

// Goes to the other state (either resized or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = 'block';
}

changeBodyElementStyle();
checkIfReady();
//-->
</script>
</body>
</html>

Test adunit name: ali_resizeBanner

Sample code for in-app: Mobile Expandable Banner (MRAID 2.0) Using Default Close Button

This template is a two component ad unit that starts off as a bottom screen banner.

If a user clicks on the banner, then the ad will expand to cover the whole screen. If the bigger ad is clicked on, then the user is redirected to a specific website. This template uses the default MRAID close button.

Behavior and UI elements

The creative comprises the following UI elements:

  • Creative Assets:
    • Banner Image component (height and width are also required)
    • Expand Banner component
  • Can change the background color of the banner ad and the expanded ad
Name Type Required Description
Banner Image File File Yes Image that will be displayed in the banner ad.
Banner Image Height Number Yes The height of the banner image.
Banner Image Width Number Yes The width of the banner image.
Background Color Text Yes The background color of the space occupied by the banner image.
ClickThrough URL URL Yes The URL that the user will be redirected to when the resized ad has been clicked on.
Expanded Image File File Yes The image that will be displayed when the banner has been clicked on.
Expanded Image Height Number Yes The height of the expanded image.
Expanded Image Width Number Yes The width of the expanded image.
 

       
<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
<head>
<script type="text/javascript" src="mraid.js"></script>
</head>
<body>
<div id="normal" style="display:none; margin:auto;top:0px;text-align:center">
<a onClick="expand();">
<img width="[%BannerImageWidth%]" height="[%BannerImageHeight%]" src="[%BannerImageFile%]" />
</a>
</div>
<div id="expanded" style="display:none;top:0px;text-align:center">
<a onClick="openURL()">
<img width="[%ExpandedImageWidth%]"  height="[%ExpandedImageHeight%]" src="[%ExpandedImageFile%]" />
</a>
</div>

<script>
<!--

function openURL() {
  mraid.open("%%CLICK_URL_ESC%%[%ClickThroughURL%]");
}

// Change background color if present
function changeBodyElementStyle() {
  if ("[%BackgroundColor%]") {
    var bodyElement = document.body;
    bodyElement.style.backgroundColor = "[%BackgroundColor%]";
  }
}	

// Check whether MRAID is ready by adding event listener
function checkIfReady(){
  if(mraid.getState() == 'loading'){
    mraid.addEventListener("ready", mraidIsReady);
  } else{
    showMyAd();
  }
}

// Once MRAID is ready, it does not need to listen to the ready event anymore
function mraidIsReady(){
  mraid.removeEventListener("ready", mraidIsReady); 
  showMyAd();
}

function showMyAd(){
  // Displays the advert
  var advertElement = document.getElementById("normal");
  advertElement.style.display = "inline";

  // Add event listener to detect whether to expand or not
  mraid.addEventListener("stateChange",updateAd); 

  // Change background color of the expanded advert
  var expandedDiv = document.getElementById("expanded");
  if ("[%BackgroundColor%]") {
    expandedDiv.style.backgroundColor = "[%BackgroundColor%]";
  }
}

function expand() {
  if(mraid.getVersion()=="2.0"){
    mraid.expand();
    return false;
  }
  else {
    return true;
  }
}

// updateAd is called when mraid changes state
// Calls toggleLayer to expand/ reduce ad size
function updateAd(state){
  if (state == "expanded"){
    toggleLayer('normal', 'expanded');
  }else if(state == "default"){
    toggleLayer('expanded', 'normal');
  }
}

// Goes to the other state (either expands or banner)
function toggleLayer(fromLayer, toLayer){
  var fromLayerElem = document.getElementById(fromLayer);
  fromLayerElem.style.display = 'none';
  var toLayerElem = document.getElementById(toLayer);
  toLayerElem.style.display = "block";
}

changeBodyElementStyle();
checkIfReady();
//-->
</script>
</body>
</html>

Test adunit name: ali_expandDefaultClose

Sample code for automatically closing an interstitial
Only directly-booked interstitials can be automatically closed; interstitials served via dynamic allocation (i.e., Ad Exchange, AdSense or AdMob) can only be dismissed by the user.

To make an interstitial close after a fixed period of time:

  • Include code in the creative to close the interstitial after a fixed period of time has elapsed. The following code can be used as a template for this approach:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>
      <script type="text/javascript" src="https://www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
      <script>
        <!--
          function
          _admStartCountDown(){setTimeout('admob.opener.close()',parseInt('[%displayTime%]')*1000)}
          function
          _admOnload(){if(admob.opener.isOverlayShowing()){_admStartCountDown()}else{admob.events.addEventListener('onshow',
          _admStartCountDown)}}
          if(window.addEventListener){window.addEventListener("load",_admOnload,false)}else{window.attachEvent("onload",_admOnload)}
        //-->
      </script>
  </head>
  <body>
    [Your_AdCode_Goes_Here]
  </body>
</html>
Target window: in-app overlay window

Using admob.opener.openOverlay(), you can open a full screen overlay browser that is animated from the bottom of the screen. This browser does not include a status bar and always displays a close button at the upper-left corner. This option can work nicely for an expandable ad where the full screen unit can be hosted on a separate page.

Below is sample code for a simple banner where the full screen unit can be loaded into an overlay browser window. You should replace the following placeholder elements with your own values. If available for your network, you can use the sample code to create a creative template.

  • [BANNER_UNIT]: URL of a banner creative.
  • [WIDTH]: Width of a banner creative.
  • [HEIGHT]: Height of a banner creative.
  • [FULLSCREEN_UNIT]: URL of a full screen creative. Note: Full screen unit should include JavaScript code to parse the destination URL and redirect the user to the landing page upon receiving a click action. See Handling destination URL from a full screen unit for more details.
  • [DESTINATION_URL]: URL of a destination page.
  • [FALLBACK_URL]: Fallback destination URL to use in case JavaScript function doesn't execute.
  • [ORIENTATION]: Supported orientation for destination URL (use "p" for portrait, "l" for landscape, or omit this value to allow any orientation).

Here's a sample creative code:


<!DOCTYPE html>
<head>
<meta name="viewport" 
content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="https://www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
</head>

<body>
<a href="[FALLBACK_CLICKURL]" 
onClick="admob.opener.openOverlay('%%CLICK_URL_ESC%%[FULLSCREEN_UNIT]?destination=[DESTINATION_URL]', 
'[ORIENTATION]'); return false;"><img border="0" 
src="[BANNER_UNIT]" width="[WIDTH]" height="[HEIGHT]"></a>
</body>
</html>

Handling destination URL from a full screen unit

The admob.opener.openOverlay() function does not have the option to specify the destination URL of the html content.

Assuming that you've passed the destination URL in the form of key-value pair when specifying the fullscreen unit, e.g. "https://link.to.fullscreen.unit?destination=https://my.destination.url", you can write a simple JavaScript function and include a snippet of HTML code to capture the click and redirect the user to the destination page.

Here's a sample page source:


<!DOCTYPE html>
<head>
<meta name="viewport" 
content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>

<script type="text/javascript" src="https://www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>

<script type="text/javascript">
function destinationUrl() {
  // Get current url after ?
  var destinationUrl = window.location.search;

  // Strip off the leading '?'
  destinationUrl = destinationUrl.substring(1);
  // Parse destination=url key-value pair
  var kvPair = destinationUrl.split("=");
  var key = kvPair[0]; // key: destination
  var value = kvPair[1]; // value: url
  var url = decodeURIComponent(value); 

  // Open destination inside overlay
  window.location = url;

  // Open destination in an external browser
  // admob.opener.openUrl(url, true);
}
</script>
</head>

<body>
<div style="position:relative;">
<!-- Load content source into an iframe -->
<iframe src="https://creative.admob.com/t1/bestBuy/tradeinJul/gi/" 
align="middle" frameborder=0 width=320 height=480 marginheight=0 marginwidth=0 scrolling=no></iframe>
<!-- Create a clickable area -->
<a href="#" onClick="destinationUrl(); return false;" style="position:absolute; top:0; left:0; 
display:inline-block; width:320px; height:480px; z-index:5;"></a>
</div>
</body>
</html>

MRAID compatibility

The Google Mobile Ads SDK supports the IAB's Mobile Rich Media Ad Interface Definitions (MRAID) standard for advertising in mobile apps. You can set a line item as MRAID v1 or MRAID v2 through the line item targeting settings, under Add targeting > Device capability.

MRAID requirements:

  • MRAID v2 requires Google Play services v7.8 or higher for Android and Google Mobile Ads SDK v7.4.0 or higher for iOS.
  • MRAID v3 requires Google Play services v15.0.0 or higher for Android and Google Mobile Ads SDK v7.30.0 or higher for iOS.

To use MRAID functions in your ad creatives, you must import mraid.js into your creative. To do this, include <script src="mraid.js"> in your creative. The Google Mobile Ads SDK, as an MRAID-compatible SDK, will look for that code in the creative and replace it with an actual URL pointing to an implementation of MRAID. Other SDKs that support MRAID will do the same though their actual URLs would be different.

You can optionally include the MRAID libraries, as well as the Google Mobile Ads SDK functionality, in the same creative.

mraid.resize() and other similar functions won't have any effect until after the ad is clicked. This prevents a malicious creative from automatically resizing and taking up the entire screen.

Learn more about MRAID support in the developer documentation. Android | iOS

Was this helpful?
How can we improve it?