Front-End Web & Mobile

Use Amazon Mobile Analytics with your JavaScript enabled apps

Update: April 30, 2018: We’ve discontinued Amazon Mobile Analytics. Amazon Pinpoint now provides the analytics features that Amazon Mobile Analytics previously offered. If you’re new to Mobile Analytics, you can integrate the mobile analytics features of Amazon Pinpoint into your app. If you currently use Amazon Mobile Analytics, you can migrate to Amazon Pinpoint.


Since our launch of Amazon Mobile Analytics last year, we have heard from many app developers who wanted to use Amazon Mobile Analytics with their apps that are built with JavaScript based frameworks.  To address these requests, we are releasing the Amazon Mobile Analytics SDK for JavaScript today.  With this release you can now integrate Amazon Mobile Analytics with web apps and HTML5 app frameworks.  In this blog post we’ll cover the few steps it takes to get started submitting events from a mobile app using the Amazon Mobile Analytics SDK for JavaScript.

For those who are not familiar with this service, Amazon Mobile Analytics lets you simply and cost effectively collect and analyze your application usage data. In addition to providing usage summary charts that are available for quick reference, Amazon Mobile Analytics enables you to set up automatic export of your data to Amazon S3 and Amazon Redshift so that you can analyze it directly with SQL queries or combine your data with other data sources. To learn more about Amazon Mobile Analytics click here.

In this blog post, I will go over the main steps to submit events to Amazon Mobile Analytics using PhoneGap as an example. The same general steps can be applied to any framework built around JavaScript such as AppGyver(supersonic), Appcelerator, Ionic, Famo.us, Intel XDK, and web pages.

Before you start, you will need to have Node.js and node package manager (npm) installed. You will also need to have your Amazon Mobile Analytics App ID and Amazon Cognito Identity Pool ID on hand. To get a new App ID and Cognito Identity Pool ID, simply log into the Amazon Mobile Analytics console and select “Add an App” from the drop down menu and complete the steps to create a new app. After following the instructions, you will end up with a Cognito Identity Pool ID and an Amazon Mobile Analytics App ID which you will need later.

In the following steps, we will create a new PhoneGap app and integrate Amazon Mobile Analytics with that app.

Step 1: Install PhoneGap

PhoneGap is a framework for developing mobile apps by using HTML, JavaScript and CSS.  It can be installed via the Node Package Manager (npm). Please see the PhoneGap web site for more information about installing and using PhoneGap to create mobile apps.

Open a command prompt window and type the following command to install the PhoneGap command line interface (CLI):

npm install -g phonegap

Step 2: Create a PhoneGap App

Type these commands for PhoneGap to generate your app skeleton using the command line interface (CLI).

phonegap create my-app
cd my-app

Step 3: Load the Amazon Mobile Analytics JavaScript SDK

The Amazon Mobile Analytics SDK for JavaScript depends on functions within the AWS SDK for JavaScript so you will need to download both. You can download the AWS SDK for JavaScript here and the Amazon Mobile Analytics SDK for JavaScript here.

Now copy the aws-sdk.min.js and aws-sdk-mobile-analytics.min.js into your PhoneGap project under the /www/js directory.

Next, load the SDKs by adding the following script tags to /www/index.html (make sure to update the version to match the versions that were downloaded).

  <script type="text/javascript" src="js/aws-sdk.min.js"></script>
  <script type="text/javascript" src="js/aws-sdk-mobile-analytics.min.js"></script>

Be sure to place those two lines before the index.js script tag below:

  <script type="text/javascript" src="js/index.js"></script>

This is what the /www/index.html body tag would look like with all of the changes:

    <body>
        <div class="app">
            <h1>PhoneGap</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
        </div>
        <script type="text/javascript" src="js/aws-sdk.min.js"></script> 
        <script type="text/javascript" src="js/aws-sdk-mobile-analytics.min.js"></script>
        <script type="text/javascript" src='cordova.js'></script>
        <script type="text/javascript" src="js/index.js"></script>
        <script type="text/javascript">
            app.initialize();
        </script>
    </body>
 

Next, add an entry to the /config.xml file that allows your app to make calls to AWS services. Open the config.xml file and add an access tag as follows:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.myapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <!-- ... -->
    <access origin="*.amazonaws.com" />
    <!-- ... -->
</widget>

Step 4: Initialize the Amazon Mobile Analytics JavaScript SDK

Open the /www/js/index.js file.  We’ll need to add a few lines in the onDeviceReady function.

First, add the Cognito Identity Credentials by adding the following lines to the  (replace “YOUR_IDENTITY_POOL_ID” with your Cognito Identity Pool ID).

AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'YOUR_IDENTITY_POOL_ID'
}); 

Next, load the credentials and initialize the client by adding the following (replace “YOUR_MOBILE_ANALYTICS_APP_ID” with your Amazon Mobile Analytics App ID). Note that the valid values for the platform attribute are ‘iPhoneOS’ and ‘Android’.  For a list of all options, please see the following documentation.

var options = {
    appId : 'YOUR_MOBILE_ANALYTICS_APP_ID',
    platform: 'Android',
    logger: console //Remove this line to turn off log messages 
};
this.mobileAnalyticsClient = new AMA.Manager(options);
console.log('Analytics initialized');

Step 5: Submit Events

At this point you can use the Amazon Mobile Analytics SDK for JavaScript to submit events.  By default, the SDK will set the Session Length to 10 minutes (you can change this by setting the sessionLength option).  Let’s hook into the PhoneGap lifecycle events and send a stop event when the app loses focus.  The MobileAnalyticsManager provides special helper functions for stopping and starting sessions.

document.addEventListener('pause', this.mobileAnalyticsClient.stopSession.bind(this.mobileAnalyticsClient), false); 
document.addEventListener('resume', this.mobileAnalyticsClient.startSession.bind(this.mobileAnalyticsClient), false);

You can record custom events by calling the recordEvent function. Let’s record a custom event anytime the user touches the screen and record how many times it has been touched.  We’ll start with the function to record the event and a variable to track the number of touches on the main screen. Add the following code to record a custom event to your app object:

touchCount: 0,
recordTouchEvent: function(event) {
    console.log(this.mobileAnalyticsClient.recordEvent('customTouch', { 
        'screenName': 'main'}, {'touchCount': this.touchCount++ } ));
    console.log('TouchEvent received');
}

Next, we’ll add an event listener for touches and tell it to use our recordTouchEvent function as the callback. Add this call to the end of your onDeviceReady function

document.addEventListener('touchstart', this.recordTouchEvent.bind(this), false);

Here is what the /www/js/index.js app object would look like with all of the changes:

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
 
        console.log('Analytics initializing');
        AWS.config.region = 'us-east-1';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: 'YOUR IDENTITY POOL ID'
        });
 
        var options = {
            appId : 'YOUR MOBILE ANALYTICS APP ID',
            platform: 'Android',
            logger: console //Remove this line to turn of log messages 
        };
        this.mobileAnalyticsClient = new AMA.Manager(options);
        console.log('Analytics initialized');
 
        document.addEventListener('pause', this.mobileAnalyticsClient.stopSession.bind(this.mobileAnalyticsClient), false);
        document.addEventListener('resume', this.mobileAnalyticsClient.startSession.bind(this.mobileAnalyticsClient), false);
        document.addEventListener('touchstart', this.recordTouchEvent.bind(this), false);
    },
    touchCount: 0,
    recordTouchEvent: function(event) {
        console.log(this.mobileAnalyticsClient.recordEvent('customTouch', { 
            'screenName': 'main'}, {'touchCount': this.touchCount++ } ));
        console.log('Touch Event recorded');
    },
 
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
 
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
 
        console.log('Received Event: ' + id);
    }
};

Step 6: Test on physical devices

Now you can test your app on physical devices using the PhoneGap Developer App.

Start by running the following command

phonegap serve --port 3000 --no-autoreload

Once you’ve installed the Phone Gap Developer App from the app store onto your device, you can enter the IP address and Connect to see your new app.

You can find the IP address to connect to in the output of the “phonegap serve” command.

[phonegap] starting app server…
[phonegap] listening on 192.168.1.100:3000
[phonegap]
[phonegap] ctrl-c to stop the server
[phonegap]

Tap the screen to create customTouch events. With logging enabled, you should see messages related to activity with the Amazon Mobile Analytics service.

[phonegap] [console.log] TouchEvent received
[phonegap] [console.log] [Function:(AMA.Client).submitEvents]
[phonegap] [console.log] 1 events to be submitted
[phonegap] [console.log] [Function:(AMA.Client).submitEvents]
.
.
.
[phonegap] 202 https://mobileanalytics.us-east-1.amazonaws.com/2014-06-05/events

You can expect to see your events in the Amazon Mobile Analytics dashboard within 60 minutes.

Summary

With today’s release, you can now build apps that use Amazon Mobile Analytics with iOS, Android, FireOS, Unity and JavaScript.  While we used PhoneGap for this tutorial, the same general steps above can also be applied to any framework built around JavaScript (such as AppGyver(supersonic), Appcelerator, Ionic, Famo.us and Intel XDK).  Leave us a comment here and let us know how your integration with the new Amazon Mobile Analytics SDK for JavaScript worked for you and tell us what you’d like us to add next.