Collect analytics data for your App using AWS Amplify
Tags: android, java, aws, codenewbie
Published: 2020-08-09 21:35:31

Wouldn’t be great to get some insights on the behavior of your App users. This will allow you implement data driven features to drive customer adoption, engagement, and retention.

This is where AWS Amplify can help, in this post I will show you how you can integrate your Android App with AWS Amplify to achieve this. Let’s get started.

&nbsp;
<ul>
 	<li>Create a new Android Studio project using the Empty Activity template</li>
</ul>
&nbsp;

<img class="aligncenter" src="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-07-28_at_12.21.53_PM.png" alt="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-07-28_at_12.21.53_PM.png" />

&nbsp;
<ul>
 	<li>We are going to use MyAuthApplication for the name field</li>
</ul>
&nbsp;

<img class="aligncenter" src="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_4.22.47_PM.png" alt="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_4.22.47_PM.png" />

&nbsp;
<ul>
 	<li>Update build.gradle (Project: MyAuthApplication) as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        // ******* Add this line *******
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // ******* Add this line *******
        mavenCentral()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</pre>
&nbsp;
<ul>
 	<li>Update build.gradle (Module:app) as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.offlineprogrammer.myauthapplication"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // ******* Add these lines *******
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // ******* Add these lines *******
    implementation 'com.amplifyframework:core:1.1.1'
    implementation 'com.amplifyframework:aws-auth-cognito:1.1.1'

}
</pre>
&nbsp;
<ul>
 	<li>Make sure to run Gradle Sync</li>
</ul>
&nbsp;
<ul>
 	<li>Run the command below on Android Studio Terminal</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">amplify init
</pre>
&nbsp;
<ul>
 	<li>You will prompted for few details as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">? Enter a name for the project MyAnalyticsApplicati
? Enter a name for the environment amplify
? Choose your default editor: None
? Choose the type of app that you're building android
Please tell us about your project
? Where is your Res directory:  app/src/main/res
Using default provider  awscloudformation

For more information on AWS Profiles, see:
&lt;https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html&gt;

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use default
Adding backend environment amplify to AWS Amplify Console app: d36t9ma8gt1tb8

</pre>
&nbsp;
<ul>
 	<li>Once complete you will get the confirmation below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">Your project has been successfully initialized and connected to the cloud!
</pre>
&nbsp;
<ul>
 	<li>Create a new class and name it MyAnalyticsApplication</li>
</ul>
&nbsp;
<ul>
 	<li>We will use this class to initialize Amplify as below - note how the class extends from Application</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:java decode:true">public class MyAnalyticsApplication extends Application {
    private static final String TAG = "MyAnalyticsApplication";

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            Amplify.addPlugin(new AWSCognitoAuthPlugin());
            Amplify.addPlugin(new AWSPinpointAnalyticsPlugin(this));
            Amplify.configure(getApplicationContext());
            Log.i(TAG, "Initialized Amplify");
        } catch (AmplifyException error) {
            Log.e(TAG, "Could not initialize Amplify", error);
        }
    }
}
</pre>
&nbsp;
<ul>
 	<li>Update AndroidManifest.xml to add a <code>android:name</code> attribute with the value of <code>.MyAnalyticsApplication</code> as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:xhtml decode:true">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.offlineprogrammer.loginwithamazon"&gt;

    &lt;application
        android:name=".MyAnalyticsApplication"
				....</pre>
&nbsp;
<ul>
 	<li>Run the command below to configure the analytics Category</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">amplify add analytics
</pre>
&nbsp;
<ul>
 	<li>Set the details below when prompted</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">? Select an Analytics provider Amazon Pinpoint
? Provide your pinpoint resource name: myanalyticsapplicati
Adding analytics would add the Auth category to the project if not already added.
? Apps need authorization to send analytics events. Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you allow this when getting started) Yes
Successfully added auth resource locally.
Successfully added resource myanalyticsapplicati locally
</pre>
&nbsp;
<ul>
 	<li>Publish those changes by running the command below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">amplify push
</pre>
&nbsp;
<ul>
 	<li>Once complete it will display your Pinpoint Url as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">✔ All resources are updated in the cloud

Pinpoint URL to track events &lt;https://us-east-1.console.aws.amazon.com/pinpoint/&gt;.....
</pre>
&nbsp;
<ul>
 	<li>The Pinpoint console will look like this</li>
</ul>
&nbsp;

<img class="aligncenter" src="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_8.11.27_PM.png" alt="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_8.11.27_PM.png" />

&nbsp;
<ul>
 	<li>Update the activity_main.xml to add a button &amp; textview as below</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:xhtml decode:true">
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/helloTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/clickMeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Click Me!!!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/helloTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

</pre>
&nbsp;
<ul>
 	<li>Update the MainActivity.java to capture the click event the user click on the button. below is the final code of MainActivity.java</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:java decode:true">public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Button clickMeButton;
    TextView helloTextView;

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

        clickMeButton = findViewById(R.id.clickMeButton);
        helloTextView = findViewById(R.id.helloTextView);

        clickMeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AnalyticsEvent event = AnalyticsEvent.builder()
                        .name("clickMeButton")
                        .addProperty("timeClicked", Calendar.getInstance().getTime().toString())
                        .build();
                Amplify.Analytics.recordEvent(event);
                helloTextView.setText("Button Clicked");
            }
        });

    }
}
</pre>
&nbsp;
<ul>
 	<li>Run the App and click the button multiple times</li>
</ul>
&nbsp;

<img class="aligncenter size-large wp-image-697" src="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/device-2020-08-09-140910-503x1024.png" alt="" width="503" height="1024" />

&nbsp;
<ul>
 	<li>Run the command below to open the Pinpoint console</li>
</ul>
&nbsp;
<pre class="theme:dark-terminal lang:sh decode:true">amplify console analytics
</pre>
&nbsp;
<ul>
 	<li>On the console go the events and you will find the clickMeButton event as below</li>
</ul>
&nbsp;

<img class="aligncenter" src="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_10.05.13_PM.png" alt="http://www.offlineprogrammer.com/wp-content/uploads/2020/08/Screen_Shot_2020-08-08_at_10.05.13_PM.png" />

&nbsp;

Check the full code on <a href="https://github.com/offlineprogrammer/MyAnalyticsApplication">github</a> and follow me on <a href="https://twitter.com/MohammedMalaka">Twitter</a> for more tips about #coding, #learning, #technology, #Java, #JavaScript, #Autism, #Parenting...etc.

Check my Apps on <a href="https://bit.ly/3h05gQ7">Google Play