Collecting analytics data for your app can be accomplished with [Amazon Pinpoint](#using-amazon-pinpoint) or [Amazon Kinesis](#using-amazon-kinesis).

Amazon Pinpoint is a fully managed AWS service that you can use to engage with your customers across multiple messaging channels using analytics captured from the device. You can send push notifications, emails, or text messages (SMS), depending on the purpose of your campaign. Features include:

**Audience Segments** - You can define dynamic segments based on data that's reported by your application, such as operating system or mobile device type. You can also import static segments that you define outside of Amazon Pinpoint.

**Messaging Campaigns** - A campaign sends tailored messages on a schedule that you define. You can create campaigns that send mobile push, email, or SMS messages. To experiment with alternative campaign strategies, set up your campaign as an A/B test, and analyze the results with Amazon Pinpoint analytics.

**Transactional Messages** - Keep your customers informed by sending transactional mobile push and SMS messages—such as new account activation messages, order confirmations, and password reset notifications—to specific users.

**Analyze User Behavior** - You can view trends about your users' level of engagement, purchase activity, and demographics. You can monitor your message traffic with metrics for messages sent and opened. Through the Amazon Pinpoint API, your application can report custom data, which Amazon Pinpoint makes available for analysis.

The Amplify CLI helps setup and configure Pinpoint within your application and connect with the AWS Mobile SDK.

<b>
  Prerequisite:
</b> [Install and configure the Amplify CLI](/cli/start/install) <br />
<b>Recommendation:</b> [Complete the Getting Started guide](/start)

## Set Up Your Backend

1. Use the CLI to add analytics to your cloud-enabled backend and app.

   In a terminal window, navigate to your project folder (the folder that typically contains your project level `build.gradle`), and add the SDK to your app.

   ```bash
   cd ./YOUR_PROJECT_FOLDER
   amplify add analytics
   ```

2. When configuration for analytics is complete, a message appears confirming that you have configured local CLI metadata for this category. You can confirm this by viewing status.

   ```console
   $ amplify status
   | Category  | Resource name   | Operation | Provider plugin   |
   | --------- | --------------- | --------- | ----------------- |
   | Auth      | cognitoabcd0123 | Create    | awscloudformation |
   | Analytics | yourprojectname | Create    | awscloudformation |
   ```

3. To create your backend AWS resources run the following:

   ```bash
   amplify push
   ```

### Update your IAM Policy:

The Amazon Pinpoint service requires permissions defined in an IAM policy to use the `submitEvents` API. If you are using long-term AWS credentials attached to an `Amazon IAM` user, attach the following policies to the role of that `IAM` user. If you are using temporary AWS credentials vended by `Amazon Cognito Identity Pools`, then attach the following policies to the Unauthenticated and/or Authenticated `IAM` roles of your `Cognito Identity Pool`. The role you attach the policies to depends on the scope of your application. For example, if you only want events submitted when users login, attach to the authenticated role. Similarly, if you want events submitted regardless of authentication state, attach the policy to the unauthenticated role. For more information on Cognito Identities authenticated/unauthenticated roles see [here](https://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html).

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["mobiletargeting:UpdateEndpoint", "mobiletargeting:PutEvents"],
      "Resource": ["arn:aws:mobiletargeting:*:${accountID}:apps/${appId}*"]
    }
  ]
}
```

## Connect to Your Backend

Use the following steps to add analytics to your mobile app and monitor the results through Amazon Pinpoint.

## Add Analytics

1. Set up AWS Mobile SDK components by including the following libraries in your `app/build.gradle` dependencies list.

```groovy
dependencies {
  implementation 'com.amazonaws:aws-android-sdk-pinpoint:ANDROID_SDK_VERSION'
  implementation 'com.amazonaws:aws-android-sdk-mobile-client:ANDROID_SDK_VERSION'
}
```

- `aws-android-sdk-pinpoint` library enables sending analytics to Amazon Pinpoint.
- `aws-android-sdk-mobile-client` library gives access to the AWS credentials provider and configurations.

2.  Add required permissions to your app manifest.

    The AWS Mobile SDK requires the `INTERNET` and `ACCESS_NETWORK_STATE` permissions. These are defined in the `AndroidManifest.xml` file.

    ```xml
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    ```

3.  Add calls to capture session starts and stops. A session is one use of an app by the user. A session begins when an app is launched (or brought to the foreground), and ends when the app is terminated (or goes to the background). To accommodate for brief interruptions, like a text message, an inactivity period of up to 5 seconds is not counted as a new session. `Total daily sessions` shows the number of sessions your app has each day. `Average sessions per daily active user` shows the mean number of sessions per user per day.

    The following are typical places where you can instrument your app session start and stop:

    - Start a session in the `Application.onCreate()` method.

    - Start a session in the `onCreate()` method of the app's first activity.

    - Start or stop a session in the [ActivityLifecycleCallbacks](https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks) class.

    The following example shows how to start a session in the `OnCreate` event of `MainActivity`.

    ```java
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    import com.amazonaws.mobileconnectors.pinpoint.PinpointManager;
    import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration;
    import com.amazonaws.mobile.client.AWSMobileClient;
    import com.amazonaws.mobile.config.AWSConfiguration;
    import com.amazonaws.mobile.client.UserStateDetails;
    import com.amazonaws.mobile.client.Callback;
    import android.content.Context;

    public class MainActivity extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getSimpleName();

        public static PinpointManager pinpointManager;

        public static PinpointManager getPinpointManager(final Context applicationContext) {
            if (pinpointManager == null) {
                // Initialize the AWS Mobile Client
                final AWSConfiguration awsConfig = new AWSConfiguration(applicationContext);
                AWSMobileClient.getInstance().initialize(applicationContext, awsConfig, new Callback<UserStateDetails>() {
                    @Override
                    public void onResult(UserStateDetails userStateDetails) {
                        Log.i("INIT", userStateDetails.getUserState().toString());
                    }

                    @Override
                    public void onError(Exception e) {
                        Log.e("INIT", "Initialization error.", e);
                    }
                });

                PinpointConfiguration pinpointConfig = new PinpointConfiguration(
                        applicationContext,
                        AWSMobileClient.getInstance(),
                        awsConfig);

                pinpointManager = new PinpointManager(pinpointConfig);
            }
            return pinpointManager;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            final PinpointManager pinpointManager = getPinpointManager(getApplicationContext());
            pinpointManager.getSessionClient().startSession();
        }
    }
    ```

        	To stop the session, use `stopSession()` and `submitEvents()` at the last point in the session you want to capture. In this example, you are using a single Activity, so the session will stop when the MainActivity is destroyed. `onDestroy()` is usually called when the back button is pressed while in the activity.

        	```java
        	@Override
        	protected void onDestroy() {
        	    super.onDestroy();

        	    pinpointManager.getSessionClient().stopSession();
        	    pinpointManager.getAnalyticsClient().submitEvents();
        	}
        	```

## Monitor Analytics

Build and run your app to see usage metrics in Amazon Pinpoint. When you run the previous code samples, the console shows a logged Session.

1. To see visualizations of the analytics coming from your app, open your project in the Amazon Pinpoint console by running the following:

   ```bash
   amplify console analytics
   ```

2. Choose `Analytics` from the icons on the left of the console, and view the graphs of your app's usage. It may take up to 15 minutes for metrics to become visible.

   ![Shows the analytics dashboard with the usage tab highlighted](/images/getting-started-analytics.png)

Analytics events can be grouped into segments, and you can engage your users more deeply by tying their app usage behavior to push notification, email, or SMS messaging campaigns. Read more about this in the [messaging section](/sdk/push-notifications/messaging-campaign) or [click here to learn more about Amazon Pinpoint](http://docs.aws.amazon.com/pinpoint/latest/developerguide/welcome.html).
