AWS Mobile
Developer Guide

Add Analytics to the Notes App

In the previous section of this tutorial, we installed Android Studio, downloaded a sample note-taking app from GitHub, then compiled and ran it in the Android Emulator. This tutorial assumes you have completed the those steps. In this section, we will extend the notes app to include application analytics. Application analytics allow us to gather demographic information about the application usage.

You should be able to complete this section in 10-15 minutes.

Set Up Your Back End

To start, set up the mobile backend resources in AWS:

  1. Open the AWS Mobile Hub console.

  2. Choose Create on the upper left, and the type android-notes-app for the name of the Mobile Hub project.

  3. Choose Next, choose Android, and then choose Add.

  4. Choose Download Cloud Config, and save awsconfiguration.json. This file the configuration to connect your app to your backend.

  5. Choose Next and then choose Done to create the project.

Used in this section

AWS Mobile Hub: Configure your mobile app's AWS backend in minutes, and then to manage those resources as your app evolves.

Add Permissions to the AndroidManifest.xml

  1. Open the project in Android Studio.

  2. Choose Project on the left side of the project to open the project browser. Find the app manifest by changing the project browser view menu at the top to Android, and opening the app/manifests folder.

  3. Add the INTERNET, ACCESS_NETWORK_STATE, and ACCESS_WIFI_STATE: permissions to your project's AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="" package=""> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:name=".Application"> <!-- Other settings --> </application> </manifest>

Add AWS SDK for Android library

  1. Edit the app/build.gradle file. Add the following lines to the

    dependencies section:

    dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) implementation '' implementation '' implementation '' implementation '' implementation '' implementation '' implementation '' implementation 'joda-time:joda-time:2.9.9' // AWS Mobile SDK for Android implementation 'com.amazonaws:aws-android-sdk-core:2.6.+' implementation 'com.amazonaws:aws-android-sdk-auth-core:2.6.+@aar' implementation 'com.amazonaws:aws-android-sdk-pinpoint:2.6.+' }
  2. Choose Sync Now on the upper right to incorporate the dependencies you just declared.

Integrate the AWS Configuration File

First, create a raw resource folder to store the AWS configuration file:

  1. Expand the app folder.

  2. Right-click the res folder.

  3. Choose New > Directory.

  4. Type raw.

                  Image of creating a raw directory in Android Studio.
  5. Choose OK.

  6. Copy the awsconfiguration.json file from its download location to the app/src/main/res/raw directory.

Android gives a resource ID to any arbitrary file placed in the raw folder, making it easy to reference in the app.


Use Reveal in Finder

If you are having trouble locating the right directory on disk, use Android Studio. Right-click the raw folder, then select Reveal in Finder. A new window with the location of the raw directory pre-loaded will appear.

Create an Singleton Class

In our sample, all access to AWS is consolidated into a singleton class called

  1. Expand app/java in the Android Studio project explorer.

  2. Right-click the directory.

  3. Select New > Java Class.

  4. Enter the details:

    • Name: AWSProvider

    • Kind: Singleton

  5. Choose OK.

You may be asked if you want to add the file to Git. Choose Yes.

The following is the initial code in this class:

package; import android.content.Context; import com.amazonaws.auth.AWSCredentialsProvider; import; import; import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration; import com.amazonaws.mobileconnectors.pinpoint.PinpointManager; public class AWSProvider { private static AWSProvider instance = null; private Context context; private AWSConfiguration awsConfiguration; private PinpointManager pinpointManager; public static AWSProvider getInstance() { return instance; } public static void initialize(Context context) { if (instance == null) { instance = new AWSProvider(context); } } private AWSProvider(Context context) { this.context = context; this.awsConfiguration = new AWSConfiguration(context); IdentityManager identityManager = new IdentityManager(context, awsConfiguration); IdentityManager.setDefaultIdentityManager(identityManager); } public Context getContext() { return this.context; } public AWSConfiguration getConfiguration() { return this.awsConfiguration; } public IdentityManager getIdentityManager() { return IdentityManager.getDefaultIdentityManager(); } public PinpointManager getPinpointManager() { if (pinpointManager == null) { final AWSCredentialsProvider cp = getIdentityManager().getCredentialsProvider(); PinpointConfiguration config = new PinpointConfiguration( getContext(), cp, getConfiguration()); pinpointManager = new PinpointManager(config); } return pinpointManager; } }

What does this do?

The AWSProvider provides a central place to add code that accesses AWS resources. The constructor will load the AWS Configuration (a JSON file that you downloaded earlier) and create an IdentityManager object that is used to authenticate the device and/or user to AWS for accessing resources. The getPinpointManager() method will create a connection to Amazon Pinpoint if it doesn't exist.

Update the Application Class

All Android applications that include the AWS SDK for Android must inherit from MultiDexApplication. This has been done for you in this project. Open the file. In the onCreate() method of the Application class, add code to initialize the AWSProvider object we previously added:

public class Application extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); // Initialize the AWS Provider AWSProvider.initialize(getApplicationContext()); registerActivityLifecycleCallbacks(new ActivityLifeCycle()); } }

Update the ActivityLifeCycle Class

We use an ActivityLifeCycle to monitor for activity events like start, stop, pause and resume. We need to determine when the user starts the application so that we can send a startSession event and stopSession event to Amazon Pinpoint. Adjust the onActivityStarted() and onActivityStopped() methods as follows:

@Override public void onActivityStarted(Activity activity) { if (depth == 0) { Log.d("ActivityLifeCycle", "Application entered foreground"); AWSProvider.getInstance().getPinpointManager().getSessionClient().startSession(); AWSProvider.getInstance().getPinpointManager().getAnalyticsClient().submitEvents(); } depth++; } @Override public void onActivityStopped(Activity activity) { depth--; if (depth == 0) { Log.d("ActivityLifeCycle", "Application entered background"); AWSProvider.getInstance().getPinpointManager().getSessionClient().stopSession(); AWSProvider.getInstance().getPinpointManager().getAnalyticsClient().submitEvents(); } }

Monitor Add and Delete Events in Amazon Pinpoint

We can also monitor feature usage within our app. In this example, we will monitor how often users add and delete notes. We will record a custom event for each operation. The Delete Note operation occurs in the class. Review the onSwiped method, and add the following code:

@Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { final NoteViewHolder noteHolder = (NoteViewHolder) viewHolder; ((NotesAdapter) notesList.getAdapter()).remove(noteHolder); // Send Custom Event to Amazon Pinpoint final AnalyticsClient mgr = AWSProvider.getInstance() .getPinpointManager() .getAnalyticsClient(); final AnalyticsEvent evt = mgr.createEvent("DeleteNote") .withAttribute("noteId", noteHolder.getNote().getNoteId()); mgr.recordEvent(evt); mgr.submitEvents(); }

The Add Note operation occurs in the class. Review the saveData() method, and add code to send the custom event to Amazon Pinpoint as shown in the following fragment.

private void saveData() { // Save the edited text back to the item. boolean isUpdated = false; if (!mItem.getTitle().equals(editTitle.getText().toString().trim())) { mItem.setTitle(editTitle.getText().toString().trim()); mItem.setUpdated(; isUpdated = true; } if (!mItem.getContent().equals(editContent.getText().toString().trim())) { mItem.setContent(editContent.getText().toString().trim()); mItem.setUpdated(; isUpdated = true; } // Convert to ContentValues and store in the database. if (isUpdated) { ContentValues values = mItem.toContentValues(); if (isUpdate) { contentResolver.update(itemUri, values, null, null); } else { itemUri = contentResolver.insert(NotesContentContract.Notes.CONTENT_URI, values); isUpdate = true; // Anything from now on is an update // Send Custom Event to Amazon Pinpoint final AnalyticsClient mgr = AWSProvider.getInstance() .getPinpointManager() .getAnalyticsClient(); final AnalyticsEvent evt = mgr.createEvent("AddNote") .withAttribute("noteId", mItem.getNoteId()); mgr.recordEvent(evt); mgr.submitEvents(); } } }

The AnalyticsClient and AnalyticsEvent classes are not imported by default. Use Alt-Return to import the missing classes.


Auto Import

You can set up Auto-Import to automatically import classes that you need. On Windows or Linux, you can find Auto-Import under File > Settings. On a Mac, you can find the same area under Android Studio > Preferences. The auto-import setting is under Editor > General > Auto Import >Java. Change Insert imports on paste to All and select the Add unambiguous imports on the fly option.

Run the Project and Validate Results

Run the application in the emulator using Run > Run 'app'. It should work as before. Ensure you try to add and delete some notes to generate some traffic that can be shown in the Pinpoint console.

To view the demographics and custom events:

  1. Open the AWS Mobile Hub console.

  2. Choose your project.

  3. Choose the Analytics icon on the left, to navigate to your project in the AWS Pinpoint console.

  4. Choose Analytics on the left.

  5. You should see an up-tick in several graphs:

                  Image of the Amazon Pinpoint console.
  6. Choose Demographics to view the demographics information.

                  Image of the Amazon Pinpoint console Demographics tab.
  7. Choose Events.

  8. Use the Event drop down to show only the AddNote event.

                  Image of the Add note event in the Amazon Pinpoint.

If you see data within each page, you have successfully added analytics to your app. Should you release your app on the App Store, you can come back here to see more details about your users.

Next steps