Events

You are currently viewing the AWS SDK for Mobile documentation which is a collection of low-level libraries. Use the Amplify libraries for all new app development. Learn more

You can use the AWS Android SDK for Pinpoint to report usage data, or events, to Amazon Pinpoint. You can report events to capture information such as session times, users’ purchasing behavior, sign-in attempts, or any custom event type that you need.

After your application reports events, you can view analytics in the Amazon Pinpoint console. The charts on the Analytics page provide metrics for many aspects of user behavior. For more information, see Chart Reference for Amazon Pinpoint Analytics in the Amazon Pinpoint User Guide.

To analyze and store your event data outside of Amazon Pinpoint, you can configure Amazon Pinpoint to stream the data to Amazon Kinesis. For more information, see Streaming Amazon Pinpoint Events to Kinesis.

By using the PinpointManager in AWS Android SDK for Pinpoint, you can call the Amazon Pinpoint API to report the following types of events:

Session events

Indicate when and how often users open and close your app.

After your application reports session events, use the Analytics page in the Amazon Pinpoint console to view charts for Sessions, Daily active endpoints, 7-day retention rate, and more.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.SessionClient;
2
3/**
4 * Call this method to start and stop a session and submit events recorded
5 * in the current session.
6 */
7public void logSession() {
8 SessionClient sessionClient = pinpointManager.getSessionClient();
9 sessionClient.startSession();
10 sessionClient.stopSession();
11 pinpointManager.getAnalyticsClient().submitEvents();
12}

Custom events

Are nonstandard events that you define by assigning a custom event type. You can add custom attributes and metrics to a custom event.

On the Analytics page in the console, the Events tab displays metrics for all custom events that are reported by your app. Use graphs of your custom usage event data in the Amazon Pinpoint console. Visualize how your users’ behavior aligns with a model you design using Amazon Pinpoint Funnel Analytics, or use stream the data for deeper analysis.

Use the following steps to implement Amazon Pinpoint custom analytics for your app.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent;
2
3/**
4* Call this method to log a custom event to the analytics client.
5*/
6public void logEvent() {
7 final AnalyticsEvent event =
8 pinpointManager.getAnalyticsClient().createEvent("EventName")
9 .withAttribute("DemoAttribute1", "DemoAttributeValue1")
10 .withAttribute("DemoAttribute2", "DemoAttributeValue2")
11 .withMetric("DemoMetric1", Math.random());
12 pinpointManager.getAnalyticsClient().recordEvent(event);
13 pinpointManager.getAnalyticsClient().submitEvents();
14}

Build, run, and use your app. Then, view your custom events on the Events tab of the Amazon Pinpoint console (choose Analytics>Events). Look for the name of your event in the Events menu.

Monetization events

Report the revenue that’s generated by your application and the number of items that are purchased by users.

On the Analytics page, the Revenue tab displays charts for Revenue, Paying users, Units sold, and more.

Use the following steps to implement Amazon Pinpoint monetization analytics for your app.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.monetization.AmazonMonetizationEventBuilder;
2
3/**
4* Call this method to log a monetized event to the analytics client.
5*/
6public void logMonetizationEvent() {
7 final AnalyticsEvent event =
8 AmazonMonetizationEventBuilder.create(pinpointManager.getAnalyticsClient())
9 .withCurrency("USD")
10 .withItemPrice(10.00)
11 .withProductId("DEMO_PRODUCT_ID")
12 .withQuantity(1.0)
13 .withProductId("DEMO_TRANSACTION_ID").build();
14 pinpointManager.getAnalyticsClient().recordEvent(event);
15 pinpointManager.getAnalyticsClient().submitEvents();
16}

Authentication events

Indicate how frequently users authenticate with your application.

On the Analytics page, the Users tab displays charts for Sign-ins, Sign-ups, and Authentication failures.

To learn how frequently users authenticate with your app, update your application code so that Amazon Pinpoint receives the following standard event types for authentication:

  • _userauth.sign_in
  • _userauth.sign_up
  • _userauth.auth_fail

You can report authentication events by doing either of the following:

Managing user sign-up and sign-in with Amazon Cognito user pools

Amazon Cognito user pools are user directories that make it easier to add sign-up and sign-in to your app. As users authenticate with your app, Amazon Cognito reports authentication events to Amazon Pinpoint. For more information, see Using Amazon Pinpoint Analytics with Amazon Cognito User Pools in the Amazon Cognito Developer Guide. Also update awsconfiguration.json by adding the pinpoint appid under CognitoUserPool.

1"CognitoUserPool": {
2 "Default": {
3 "PoolId": "<poolid>",
4 "AppClientId": "<appclientid>",
5 "Region": "<region>",
6 "PinpointAppId": "<pinpointappid>"
7 }
8}

Reporting authentication events by using the Amazon Pinpoint client that’s provided by the AWS Mobile SDK for Android.

If you don’t want to use Amazon Cognito user pools, you can use the Amazon Pinpoint client to record and submit authentication events, as shown in the following examples. In these examples, the event type is set to _userauth.sign_in, but you can substitute any authentication event type.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent;
2
3/**
4* Call this method to log an authentication event to the analytics client.
5*/
6public void logAuthenticationEvent() {
7 final AnalyticsEvent event =
8 pinpointManager.getAnalyticsClient().createEvent("_userauth.sign_in");
9 pinpointManager.getAnalyticsClient().recordEvent(event);
10 pinpointManager.getAnalyticsClient().submitEvents();
11}

Custom App events

Instrument your code to capture app usage event information, including attributes you define. Use graphs of your custom usage event data in the Amazon Pinpoint console. Visualize how your users' behavior aligns with a model you design using Amazon Pinpoint Funnel Analytics, or use stream the data for deeper analysis.

Use the following steps to implement Amazon Pinpoint custom analytics for your app.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent;
2
3/**
4* Call this method to log a custom event to the analytics client.
5*/
6public void logEvent() {
7 final AnalyticsEvent event =
8 pinpointManager.getAnalyticsClient().createEvent("EventName")
9 .withAttribute("DemoAttribute1", "DemoAttributeValue1")
10 .withAttribute("DemoAttribute2", "DemoAttributeValue2")
11 .withMetric("DemoMetric1", Math.random());
12
13 pinpointManager.getAnalyticsClient().recordEvent(event);
14}

Build, run, and use your app. Then, view your custom events on the Events tab of the Amazon Pinpoint console (choose Analytics>Events). Look for the name of your event in the Events menu.

Enable Revenue Analytics

Amazon Pinpoint supports the collection of monetization event data. Use the following steps to place and design analytics related to purchases through your app.

1import com.amazonaws.mobileconnectors.pinpoint.analytics.monetization.AmazonMonetizationEventBuilder;
2
3/**
4* Call this method to log a monetized event to the analytics client.
5*/
6public void logMonetizationEvent() {
7 final AnalyticsEvent event =
8 AmazonMonetizationEventBuilder.create(pinpointManager.getAnalyticsClient())
9 .withCurrency("USD")
10 .withItemPrice(10.00)
11 .withProductId("DEMO_PRODUCT_ID")
12 .withQuantity(1.0)
13 .withProductId("DEMO_TRANSACTION_ID").build();
14 pinpointManager.getAnalyticsClient().recordEvent(event);
15}

Event Ingestion Limits

The limits applicable to the ingestion of events using the AWS Android SDK for Pinpoint and the Amazon Pinpoint Events API can be found here.

Managing Sessions in Your Application

As users engage with your app, it reports information about app sessions to Amazon Pinpoint, such as session start times, session end times, and events that occur during sessions. To report this information from an Android application, your app must include methods that handle events as your app enters the foreground and the background on the user's Android device.

Example Lifecycle Manager

The following example class, AbstractApplicationLifeCycleHelper, implements the Application.ActivityLifecycleCallbacks interface to track when the application enters the foreground or background, among other states. Add this class to your app, or use it as an example for how to update your code:

1package com.amazonaws.mobile.util;
2
3import android.app.Activity;
4import android.app.Application;
5import android.content.BroadcastReceiver;
6import android.content.Context;
7import android.content.Intent;
8import android.content.IntentFilter;
9import android.os.Bundle;
10import android.util.Log;
11
12import java.util.WeakHashMap;
13
14/**
15 * Aids in determining when your application has entered or left the foreground.
16 * The constructor registers to receive Activity lifecycle events and also registers a
17 * broadcast receiver to handle the screen being turned off. Abstract methods are
18 * provided to handle when the application enters the background or foreground.
19 * Any activity lifecycle callbacks can easily be overridden if additional handling
20 * is needed. Just be sure to call through to the super method so that this class
21 * will still behave as intended.
22 **/
23public abstract class AbstractApplicationLifeCycleHelper implements Application.ActivityLifecycleCallbacks {
24 private static final String LOG_TAG = AbstractApplicationLifeCycleHelper.class.getSimpleName();
25 private static final String ACTION_SCREEN_OFF = "android.intent.action.SCREEN_OFF";
26 private boolean inForeground = false;
27 /** Tracks the lifecycle of activities that have not stopped (including those restarted). */
28 private WeakHashMap<Activity, String> activityLifecycleStateMap = new WeakHashMap<>();
29
30 /**
31 * Constructor. Registers to receive activity lifecycle events.
32 * @param application The Android Application class.
33 */
34 public AbstractApplicationLifeCycleHelper(final Application application) {
35 application.registerActivityLifecycleCallbacks(this);
36 final ScreenOffReceiver screenOffReceiver = new ScreenOffReceiver();
37 application.registerReceiver(screenOffReceiver, new IntentFilter(ACTION_SCREEN_OFF));
38 }
39
40 @Override
41 public void onActivityCreated(final Activity activity, final Bundle bundle) {
42 Log.d(LOG_TAG, "onActivityCreated " + activity.getLocalClassName());
43 handleOnCreateOrOnStartToHandleApplicationEnteredForeground();
44 activityLifecycleStateMap.put(activity, "created");
45 }
46
47 @Override
48 public void onActivityStarted(final Activity activity) {
49 Log.d(LOG_TAG, "onActivityStarted " + activity.getLocalClassName());
50 handleOnCreateOrOnStartToHandleApplicationEnteredForeground();
51 activityLifecycleStateMap.put(activity, "started");
52 }
53
54 @Override
55 public void onActivityResumed(final Activity activity) {
56 Log.d(LOG_TAG, "onActivityResumed " + activity.getLocalClassName());
57 activityLifecycleStateMap.put(activity, "resumed");
58 }
59
60 @Override
61 public void onActivityPaused(final Activity activity) {
62 Log.d(LOG_TAG, "onActivityPaused " + activity.getLocalClassName());
63 activityLifecycleStateMap.put(activity, "paused");
64 }
65
66 @Override
67 public void onActivityStopped(final Activity activity) {
68 Log.d(LOG_TAG, "onActivityStopped " + activity.getLocalClassName());
69 // When the activity is stopped, you remove it from the lifecycle state map since you
70 // no longer consider it keeping a session alive.
71 activityLifecycleStateMap.remove(activity);
72 }
73
74 @Override
75 public void onActivitySaveInstanceState(final Activity activity, final Bundle outState) {
76 Log.d(LOG_TAG, "onActivitySaveInstanceState " + activity.getLocalClassName());
77 }
78
79 @Override
80 public void onActivityDestroyed(final Activity activity) {
81 Log.d(LOG_TAG, "onActivityDestroyed " + activity.getLocalClassName());
82 // Activity should not be in the activityLifecycleStateMap any longer.
83 if (activityLifecycleStateMap.containsKey(activity)) {
84 Log.wtf(LOG_TAG, "Destroyed activity present in activityLifecycleMap!?");
85 activityLifecycleStateMap.remove(activity);
86 }
87 }
88
89 /**
90 * Call this method when your Application trims memory.
91 * @param level the level passed through from Application.onTrimMemory().
92 */
93 public void handleOnTrimMemory(final int level) {
94 Log.d(LOG_TAG, "onTrimMemory " + level);
95 // If no activities are running and the app has gone into the background.
96 if (level >= Application.TRIM_MEMORY_UI_HIDDEN) {
97 checkForApplicationEnteredBackground();
98 }
99 }
100
101 class ScreenOffReceiver extends BroadcastReceiver {
102 @Override
103 public void onReceive(Context context, Intent intent) {
104 checkForApplicationEnteredBackground();
105 }
106 }
107
108 /**
109 * Called back when your application enters the Foreground.
110 */
111 protected abstract void applicationEnteredForeground();
112
113 /**
114 * Called back when your application enters the Background.
115 */
116 protected abstract void applicationEnteredBackground();
117
118 /**
119 * Called from onActivityCreated and onActivityStarted to handle when the application enters
120 * the foreground.
121 */
122 private void handleOnCreateOrOnStartToHandleApplicationEnteredForeground() {
123 // if nothing is in the activity lifecycle map indicating that you are likely in the background, and the flag
124 // indicates you are indeed in the background.
125 if (activityLifecycleStateMap.size() == 0 && !inForeground) {
126 inForeground = true;
127 // Since this is called when an activity has started, you now know the app has entered the foreground.
128 applicationEnteredForeground();
129 }
130 }
131
132 private void checkForApplicationEnteredBackground() {
133 ThreadUtils.runOnUiThread(new Runnable() {
134 @Override
135 public void run() {
136 // If the App is in the foreground and there are no longer any activities that have not been stopped.
137 if ((activityLifecycleStateMap.size() == 0) && inForeground) {
138 inForeground = false;
139 applicationEnteredBackground();
140 }
141 }
142 });
143 }
144}

Reporting Session Events

After you include the AbstractApplicationLifeCycleHelper class, implement the two abstract methods, applicationEnteredForeground and applicationEnteredBackground, in the Application class. These methods enable your app to report the following information to Amazon Pinpoint:

  1. Session start times (when the app enters the foreground).

  2. Session end times (when the app enters the background).

  3. The events that occur during the app session, such as monetization events. This information is reported when the app enters the background.

The following example shows how to implement applicationEnteredForeground and applicationEnteredBackground. It also shows how to call handleOnTrimMemory from inside the onTrimMemory function of the Application class:

1import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration;
2import com.amazonaws.mobileconnectors.pinpoint.PinpointManager;
3
4public class Application extends MultiDexApplication {
5 public static PinpointManager pinpointManager;
6 private AbstractApplicationLifeCycleHelper applicationLifeCycleHelper;
7
8 @Override
9 public void onCreate() {
10 super.onCreate();
11
12 // . . .
13
14 // The Helper registers itself to receive application lifecycle events when it is constructed.
15 // A reference is kept here in order to pass through the onTrimMemory() call from
16 // the Application class to properly track when the application enters the background.
17 applicationLifeCycleHelper = new AbstractApplicationLifeCycleHelper(this) {
18 @Override
19 protected void applicationEnteredForeground() {
20 Application.pinpointManager.getSessionClient().startSession();
21 // handle any events that should occur when your app has come to the foreground...
22 }
23
24 @Override
25 protected void applicationEnteredBackground() {
26 Log.d(LOG_TAG, "Detected application has entered the background.");
27 Application.pinpointManager.getSessionClient().stopSession();
28 Application.pinpointManager.getAnalyticsClient().submitEvents();
29 // handle any events that should occur when your app has gone into the background...
30 }
31 };
32 }
33
34 private void updateGCMToken() {
35 try {
36 final String gcmToken = InstanceID.getInstance(this).getToken(
37 "YOUR_SENDER_ID",
38 GoogleCloudMessaging.INSTANCE_ID_SCOPE
39 );
40 Application.pinpointManager.getNotificationClient().registerGCMDeviceToken(gcmToken);
41 } catch (IOException e) {
42 e.printStackTrace();
43 }
44 }
45
46 @Override
47 public void onTrimMemory(final int level) {
48 Log.d(LOG_TAG, "onTrimMemory " + level);
49 applicationLifeCycleHelper.handleOnTrimMemory(level);
50 super.onTrimMemory(level);
51 }
52
53}

You've updated your Android app to report session information. Now, when users open and close your app, you can see session metrics in the Amazon Pinpoint console, including those shown by the Sessions and Session heat map charts.