Integrating Ads with the Amazon Mobile Ads API

PreviousTable of ContentsNext
A Simple Amazon In-App Purchasing Example ApplicationA Kindle Fire Amazon Mobile Ads API Example Application


<google>BUY_KINDLE_FIRE</google>


Application sales and in-app purchases are not the only ways to generate revenue from a Kindle Fire-based Android application. A third option exists in the form of advertisement placements within applications. With the introduction of the Amazon Mobile Ads API, it is now a relatively simple process to incorporate ads provided by Amazon into an application with just a few lines of code.

This chapter will provide an overview of the Amazon Mobile Ads API before working through an example implementation in the next chapter.

The Amazon Mobile Ads API

The purpose of the Amazon Mobile Ads API is to allow application developers to quickly and easily integrate advertisements into Android applications running on Kindle Fire and other Android based devices (as long as those applications are distributed via the Amazon App Store). The ads displayed are supplied by the Amazon Mobile Ad Network and the developer is paid on the basis of impressions using a cost-per-thousand impressions (CPM) model.

The API provides advertisement options for a variety of ad sizes and types, though it is important to be aware that not all sizes are supported on all device types. At the time of writing the ad sizes supported by the API are as follows:

  • 300x50 – Android phone devices only
  • 320x50 – Android phone devices only
  • 300x250 – All device types
  • 600x90 – Kindle Fire and Android tablets only
  • 728x90 – Android tablet devices only
  • 1024x50 - Kindle Fire and Android tablets only

In terms of ad types, the API supports both static banners and rich media expandable banners. Static banner ads typically open a separate web browser session when selected by the user. Rich media banners, on the other hand, expand within the application to display interactive media based content such as video and audio.

Ad Targeting Options

In addition to selecting the size of the ads to appear within an Android application, the API also allows a number of additional options to be specified that control the nature of the ads displayed to the user:

  • Location – The application may enable the Amazon Ads Network to display ads that are relevant to the current location of the device. This, for example, might allow ads to be served to promote a nearby restaurant.
  • Gender – In the event that the application knows the gender of the user (either because the application has gathered this information or simply because it is the target demographic), it can request that ads targeted to either male or female users be displayed.
  • Floor Price – This option allows a minimum CPM price to be set for ads displayed within the application. The price is set using “micro-dollars” where 1 cent is equal to 100,000 micro-dollars.

Amazon Mobile Ads API – The Rules of Use

There are a number of rules that must be followed when placing ads using the Amazon Mobile Ads API.

Firstly, all ads placed within an application must be visible to the user without the need to perform any scrolling. This is a concept referred to in the advertising world as “above the fold”, a reference to the days when most adverts were placed in broadsheet newspapers that the reader typically folds along a horizontal center crease in order to read more easily.

Secondly, it is possible to refresh the currently displayed ad from within the application code. In fact, this is recommended when the orientation of the device changes and the user interface is redrawn. It is also acceptable, however, to refresh the ad at specific time intervals so that a new ad appears on a screen on which the user is likely to spend a considerable amount of time. It is important, however, that these refreshes are not performed too frequently. Amazon suggests a 30 to 60 second refresh rate for such ads. More frequent refresh requests will likely result in the ad server blocking the request.

Finally, when testing an application containing ads, it is essential that the testing be performed with the ad system in test mode, details of which will be outlined later in this chapter. Clocking up large numbers of ad impressions (and thereby revenue) while testing an application may result in the termination of service.

Downloading and Installing the Amazon Mobile Ads API

The Amazon Mobile Ads API is not part of the standard Android SDK, nor is it included in the Amazon Mobile App SDK package. The API is, instead, contained within a standalone package which may be downloaded from the following URL:

https://developer.amazon.com/sdk/download/mobileads.html

The download is provided in the form of a zipped archive file which should be unpacked into a suitable location on the development system.

Providing Tax and Banking Information

Before making use of the API, it is mandatory that banking and tax information be entered using the Amazon Mobile App Distribution portal. If this information has not yet been set up, log into the portal, select the Settings tab and then enter the information requested in both the Payment Information and Tax Identity sub-categories. Note that until this information is entered, ads will most likely fail to appear with a DISABLED_APP error in the log output. Whilst this data is reviewed by Amazon, there may also be a delay between the information being entered and the ad system being enabled for your account.

Preparing a Project to use Amazon Mobile Ads

Once the Amazon Mobile Ads API has been installed, a number of steps must be taken to prepare an application project to display ads.

Adding the API JAR File to the Project

The first step is to make sure that the JAR file for the API is included in the project build properties. To perform this task, locate the project for which support is required within the Eclipse Package Explorer panel, right-click on the project name and select the Properties option from the resulting menu. Within the Properties dialog, select the Java Build Path category from the left hand panel and, within the Java Build Path panel, click on the Add External JARS… button. In the JAR selection dialog, navigate to the following location (where <ad api path> is replaced by the location on your file system where the Amazon Mobile Ads API package was installed):

<ad api path>/lib

From within the lib directory, select the amazon-ads-<ver>.jar file. At time of writing, this file is named amazon-ads-4.0.9.jar but may have been superseded since then by a newer version. Once selected, click on the Open button to add the JAR file to the project. Once added, it should be listed in the Java Build Path panel.

Assuming the JAR file is now listed, click on OK to close the Properties dialog.

Finally, the JAR file needs to be added to the libs folder of the project. Within an operating system file browser window, locate the JAR file and drag and drop it onto the libs folder of the project in the Package Explorer panel. When prompted whether to copy or link the library, select the copy option.

Obtaining the Application Key

Part of the process of displaying ads in an application involves registering the application’s key with the API. Each application added to the Amazon Mobile App Distribution portal is assigned a unique application key. Once an application has been registered, select it from the My Apps page on the portal and locate the key which will be listed on the General Information page.

Configuring the Manifest File

The Amazon Ads API requires that a number of permissions be requested within the application’s manifest file. At a minimum, the application must request permission for internet access. For full functionality, however, the application should also request network state, Wi-Fi state and location permissions as follows:

<uses-permission android:name="android.permission.INTERNET" />
<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_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

In addition, the API also requires that the MraidBrowser and VideoActionHandler actions be declared within the <application> element of the manifest file. These are required to enable rich media content to be displayed from within the application:

<activity android:name="com.amazon.device.ads.MraidBrowser" 
         android:configChanges="keyboardHidden|orientation"/>
<activity android:name="com.amazon.device.ads.VideoActionHandler" 
         android:configChanges="keyboardHidden|orientation|screenSize"/> 

Adding the Amazon Ad Resources

Ads may be added to an application either via code within an activity or by adding ad views to the XML layout resources of the user interface. In the latter case, an additional resource file must be added to the project. This file is named amazon_ads_attrs.xml and is located in the res/values folder of the location into which the Amazon Mobile Ads API was previously installed. In order to include ad views in layout resource files, this file must be added to the res/values folder of the project. This can be achieved by locating the file in a file system browser window and dragging and dropping it onto the project’s res/values folder in the Eclipse Package Explorer panel so that it appears as illustrated in Figure 45-1:


Amazon ads res File.png

Figure 45-1


Once these steps have been taken the project is ready to begin implementing ads, starting with registering the application key with the API.

Registering the Application Key

Preceding sections of this chapter outlined the steps to identify the application key for an application. Once this has been obtained, it must be registered within the application code before ads can be displayed. This needs to be performed once per application launch, so is best performed in the onCreate() method of the application’s main activity. For example:

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_ad_example);
		
	AdRegistration.setAppKey(getApplicationContext(),
		"abcdefabcdefabcdefabcdefabcdefa");
}

Writing Java Code to Display an Ad

The AdLayout view class is used to display ads within an application user interface. As previously outlined, ads may be incorporated into the user interface of an application either by writing code, or via an activity’s XML layout file. When writing code, a new instance of the AdLayout class must be created, specifying the size of ad required. This AdLayout instance is then added to the user interface and its loadAd() method called to load the ad into the view. The following code fragment, for example, creates a new 600x90 AdLayout instance, adds it to a layout manager view and then loads the ad:

AdLayout myAdView;
	
myAdView = new AdLayout(this, AdLayout.AdSize.AD_SIZE_600x90);

LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout1);
		  
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
		       LinearLayout.LayoutParams.WRAP_CONTENT,
		       LinearLayout.LayoutParams.WRAP_CONTENT);

layout.addView(myAdView, params);

AdTargetingOptions adOptions = new AdTargetingOptions();
		    
myAdView.loadAd(adOptions);

Adding an Ad to the Layout Resource File

An alternative to writing code is to include the ad in the XML layout resource file. This involves loading the Amazon namespace into the XML file and adding an AdLayout element to the design. The following XML, for example, shows a LinearLayout manager containing a single 600x90 ad view:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:Amazon="http://schemas.android.com/apk/res/com.example.adexample"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".AdExampleActivity" >
<com.amazon.device.ads.AdLayout  
        android:id="@+id/myAdView" 
        android:layout_width="600dp" 
        android:layout_height="90dp"
        Amazon:adSize="600x90"/>
</LinearLayout>

Adding the AdLayout view in the XML layout file does not entirely negate the need to write code. In order for the ad to appear, it is still necessary to make a call to the loadAd() method of the AdLayout view when the activity starts up, for example:

AdLayout myAdView = (AdLayout) findViewById(R.id.myAdView);
AdTargetingOptions adOptions = new AdTargetingOptions();
myAdView.loadAd(adOptions);

Setting Ad Targeting Options

Ad targeting options are specified by creating an appropriately configured AdTargetingOptions object and passing it through as an argument to the loadAd() method of the AdLayout view. In the preceding code examples, an empty AdTargetingOptions object was created, essentially indicating that no ad targeting was required. As previously outlined, ads may be configured based on the gender of the user, the geographical location of the device and the minimum price acceptable for the ad to display.

Enabling geographical targeting involves a call to the enableGeoLocation() method of the AdTargetingOptions instance, passing through a value of true:

AdTargetingOptions adOptions = new AdTargetingOptions();
adOptions.enableGeoLocation(true);

Similarly, gender specific targeting may be enabled via a call to the setGender() method, passing through a value of either Gender.MALE or Gender.FEMALE:

import com.amazon.device.ads.AdTargetingOptions.Gender;
.
.
AdTargetingOptions adOptions = new AdTargetingOptions();
adOptions.setGender(Gender.FEMALE);

Finally, the floor price value may be specified as a micro-dollar amount via a call to the setAdvancedOptions() method. This accepts arguments in the form of a key-value pair, where the key for the floor price option is “ec”. The following code, for example, sets the floor price to 97 cents:

AdTargetingOptions adOptions = new AdTargetingOptions();
adOptions.setGender(Gender.FEMALE);
adOptions.setAdvancedOption("ec", "970000");

Enabling Testing and Logging

When testing an application that includes Amazon Mobile Ads, it is important to remember to switch to testing mode. This prevents the ad impressions from being tracked, recorded and generating revenue. Testing mode is enabled via a call to the enableTesting() method of the AdRegistration class, passing through the activity context and a Boolean value indicating whether testing mode is being enabled or disabled:

AdRegistration.enableTesting(this, true);

A particularly useful feature when testing ad functionality involves enabling logging. When enabled, diagnostic output is sent to the LogCat panel indicating the actions performed by the Amazon Mobile Ads API along with any errors that have been encountered. To enable this mode, simply call the enableLogging() method of the AdRegistration class, once again passing through a reference to the context and a Boolean value:

AdRegistration.enableLogging(this, true);

Be sure to take steps to disable these modes before submitting a completed application to the Amazon Mobile App Distribution portal.

Tracking Events with an AdListener

Once the AdLayout view is instructed to load an ad, the API will contact the Amazon ad server to request and download an appropriate advertisement to be displayed. The amount of time this takes will depend primarily on the speed and quality of the network connection used by the device and the responsiveness of the Amazon ad servers. There may even be instances where the API fails to download an ad (for example when the device is not connected to the internet). To avoid any delay in obtaining an ad from locking up the application, the API performs the ad loading process asynchronously from the application. This allows the application to continue to run while the ad procurement is being handled. If the application does not need to wait for the API to complete this process, this raises the question of how the application receives notification of the success or otherwise of the ad download. The answer to this involves the implementation of a listener class. This is a class on which a variety of callback methods can be called by the API to notify the application of events relating to the ad system.

To configure a listener, a class that implements the AdListener interface must be specified as the listener for the AdLayout view. This can either be the activity in which the AdLayout view resides, or an entirely separate class. Regardless, in order to fully implement the interface, the class must also implement the following callback methods:

  • onAdLoaded() – This method is called each time an ad is successfully loaded. It is passed as arguments a reference to the corresponding AdLayout view and an AdProperties object containing information about the ad that was loaded. This information includes the type of ad and whether or not it expands or plays audio or video when selected by the user.
  • onAdExpanded() – This method is passed a reference to the selected AdLayout view and is called when the user selects and expands a rich media ad.
  • onAdCollapsed() – This method is passed a reference to the corresponding AdLayout view and is called after the user closes an expanded rich media ad.
  • onAdFailedToLoad() – This method is called in the event that the API failed to download an ad. The method is passed a reference to the corresponding AdLayout view together with an AdError object containing details of the reason for the failure.

In the event of a failure, the AdError object will contain an error code and a description. The application should identify the nature of the problem using this information and decide whether or not it is appropriate to retry the attempt. Details of the error codes, messages and retry rules can be found online at:

https://developer.amazon.com/sdk/mobileads/event-tracking-and-errors.html

In the event the error reported indicates that an ad is not available from the Amazon Mobile Ad Network, the onAdFailedToLoad() method is the ideal place to attempt to load an ad using an alternate ad network SDK such as AdMob.

Once a listener class has been declared it must be added to the AdLayout instance via the setListener() method, for example:

AdLayout myAdLayout = new AdLayout();
myAdLayout.setListener(adListener);

Configuring the Ad Request Timeout

By default, the Amazon Mobile Ads API will timeout after 10 seconds of attempting to download an ad at which point the onAdFailedToLoad() method of the listener (if implemented) will be called. The timeout duration may be changed by calling the setTimeout() method of the corresponding AdLayout object, passing through the new timeout duration specified in milliseconds. The following code fragment, for example, changes the timeout to 30 seconds:

myAdLayout.setTimeout(30000);

Summary

The Amazon Mobile Ads API provides a way for developers to integrate ads from the Amazon Mobile Ad Network into applications, thereby providing an additional source of revenue. Ads are presented to the user via instances of the AdLayout view class which may be configured to take advantage of a number of different ad sizes. Ads served by Amazon fall into the category of static and interactive rich media content and may be configured to target specific locations or gender. Through the implementation of a listener, the application can be configured to receive event notifications such as when the API fails to load an ad.


<google>BUY_KINDLE_FIRE</google>



PreviousTable of ContentsNext
A Simple Amazon In-App Purchasing Example ApplicationA Kindle Fire Amazon Mobile Ads API Example Application