Link Search Menu Expand Document

Snapyr For Android SDK

The Snapyr Android SDK makes it simple to connect your Android app to the Snapyr platform.

The documented references Java code but Kotlin equivalent code is fully supported as well.

Snapyr supports any Android device running API 14 (Android 4.0) and higher.

Using the Android SDK

Step 1: Install the Library

Automatically Via Gradle

We recommend using the Gradle build system, which helps keep versions under control and automates most steps. The Snapyr module is distributed via Maven Central.

Add the Snapyr module and additional dependencies to your app/build.gradle file:

dependencies {
    implementation 'com.snapyr.sdk.android:snapyr:1.+'

    // additional dependencies required by Snapyr
    implementation('androidx.lifecycle:lifecycle-process:2.2.0')
    implementation('androidx.lifecycle:lifecycle-common-java8:2.2.0')
    implementation('androidx.constraintlayout:constraintlayout:2.1.4')

    implementation('androidx.core:core')
    implementation('androidx.appcompat:appcompat:1.3.0')
}

Manually

Alternatively, you can download a .aar file of the latest version of the SDK from the Snapyr Android SDK releases page.

Add this file to your External Libraries folder and implement the Snapyr module in your app’s build.gradle file directly:

dependencies {
    implementation (name: 'snapyr', ext: 'aar')
    
    // additional dependencies required by Snapyr
    implementation('androidx.lifecycle:lifecycle-process:2.2.0')
    implementation('androidx.lifecycle:lifecycle-common-java8:2.2.0')
    implementation('androidx.constraintlayout:constraintlayout:2.1.4')

    implementation('androidx.core:core')
    implementation('androidx.appcompat:appcompat:1.3.0')
}

Step 2. Initialize

Initialize in the Application subclass. You’ll need your app’s Snapyr Write Key. To obtain your write key, please contact Snapyr Customer Service.

// Create a Snapyr client with the given Android app context and Snapyr write key.
Snapyr snapyr = new Snapyr.Builder(context, APP_WRITE_KEY)
.trackApplicationLifecycleEvents() // Enable this to record certain application events automatically
.recordScreenViews() // Enable this to record screen views automatically
.enableSnapyrPushHandling() // Enable this to use and track push notifications through Snapyr (additional setup required - see push section below)
// Add this to enable Snapyr in-app messaging. See more info in in-app section below
// NOTE: requires Snapyr SDK 1.2.0 or later
.configureInAppHandling(
    new InAppConfig()
        .setActionCallback(
                (inAppMessage) -> {
                    Log.i("MyApp", "Received Snapyr in-app message!");
                    // trigger your own callback code here
                }))
.build();

// Set the initialized instance as a globally accessible instance.
Snapyr.setSingletonInstance(snapyr);

You can also automatically track lifecycle events such as Application Opened, Application Installed, Application Updated to start quickly with core events. These are enabled by default.

Make sure to call init and Snapyr.setSingletonInstance only ONCE.

Step 3. Add Permissions

Ensure that the necessary permissions are declared in your application’s AndroidManifest.xml.

<!-- Required for internet. -->
<uses-permission android:name="android.permission.INTERNET"/>

Main Snapyr SDK Calls

Identify

This lets you setup information about the current user and tie that individual to all actions taken. You can set traits for a specific user and these traits will be tied to every tracking action taken. Note that if you do not call Identify, the Snapyr SDK will generate an AnonymousID for the user.

Snapyr.with(context).identify("<User ID>", new Traits().putValue("<Trait Name>", "<Trait Value>"), null);

Snapyr recommends that you make an Identify call once when the user first registers or logs in to his / her account, and then call Identify again if traits are added – for example if the user links her account to Facebook or email and you now have desired data. Snapyr will merge any old traits with new ones and update any traits that use the same key.

// Initially when you only know the user's name
Snapyr.with(context).identify(new Traits().putName("Larry David"));

// Sometime later in your app when the user gives you their email
Snapyr.with(context).identify(new Traits().putEmail("larry@curbyourenthusiasm.com"));

Remember, you can replace the properties and traits in the code samples with variables that represent the data you actually collected.

The Identify call has the following fields:

userId String,optional The unique ID for this user that your app uses.
traits Traits,optional A map of traits about the user, such as their first name, Facebook ID, email address, etc. This map must be flat. All keys are strings, and supported value types are string, boolean, integer, and float.

The SDK automatically sends the userId and anonymousId as traits.

Track

The Track call is at the heart of Snapyr and allows you to keep track of events or actions your users perform. Every event can also have associated properties.

Snapyr.with(context).track("<Event Name>", new Properties().putValue("<Property Name>", "<Property Value>"));

By default, Snapyr is checking the application lifecycle events and tracks a few key common events automatically such as the Application Installed, Application Updated and Application Opened. You can turn automatic tracking off during initialization.

You might also want to track events that indicate key spots hit such as Registered, Logged In, Complete Tutorial, or Purchased an Item.

An example track call:

Snapyr.with(this).track("Opened Loot Crate", new Properties().putValue("type", "epic"));

This example Track call tells us that your user just triggered the “Open Loot Crate” event with a type of “Epic.”

The Track call properties can be anything you want to record. For example:

Snapyr.with(this).track("Purchased Item", new Properties().putSku("gold_bag").putRevenue(99.99));

The Track call includes the following fields:

name String,required A name for the tracked action.
properties Properties, optional A map of properties for this action, e.g. revenue if the action was a purchase. This map must be flat. All keys are strings, and supported value types are string, boolean, integer, and float.

Retrieve AnonymousId

By default, a Snapyr user will be granted an anonymousID String tied to his or her device (if you don’t set one up explicitly using the Identity method). You can get this ID using the method:

Snapyr.with(context).getSnapyrContext().traits().anonymousId();

Reset

The Reset method can clear the SDK’s internal data for the current user, such as user traits. This is useful if a user logs out so that multiple users with different identities can be tracked properly. Note that when you call Reset, Snapyr will assign the new user an AnonymousID until a new id is explicitly set via the Identify method.

Snapyr.with(context).reset();

Collecting Stats

If you want to track how many events you send to Snapyr or other key stats, you can get a snapshot and then log it as follows:

StatsSnapshot snapshot = Snapyr.with(context).getSnapshot();
log(snapshot.integrationOperationAverageDuration);
log(snapshot.flushCount);

Debug Logging

If you want to dive deeper into the Snapyr SDK and all of the events it is sending, you can enable logging.

Snapyr snapyr = new Snapyr.Builder(context, writeKey).logLevel(LogLevel.VERBOSE)...build();

You can disable logging completely (LogLevel.NONE), enable basic logging (LogLevel.BASIC), enable a bit more info (LogLevel.INFO), or simply log everything (LogLevel.VERBOSE).

We recommend setting LogLevel to NONE for the production build of your app or game.

Opt-out

Due to various laws or age groups, you may need to opt out of tracking. You can turn tracking off using:

Snapyr.with(this).optOut(true);

This flag persists across device reboots, so you can call it once (such as in a settings screen) and Snapyr will remember your decision.

In-App Messaging

The Snapyr SDK makes it easy to handle in-app messages that are triggered by a Snapyr campaign.

Snapyr supports two different types of messages:

  • HTML overlay: if your campaign sends this type of message, the Snapyr SDK will render a window over your application showing the message automatically.
  • Custom: if your campaign sends this type of message, the Snapyr SDK will call a callback that you provide at config time. You can then decide how to use the data in this message - for example, you might update your user’s account balance, or jump to a different screen in your app.

Configuration

To get started, all you need to do is include a call to .configureInAppHandling() when initializing Snapyr, and provide a couple of details. See above for more information about intialization.

NOTE: In-app messaging requires Snapyr SDK version 1.2.0 or later.

// Create a Snapyr client with the given Android app context and Snapyr write key.
Snapyr snapyr = new Snapyr.Builder(context, APP_WRITE_KEY)
... // other config options here...
.configureInAppHandling( // add this to enable in-app messaging
    new InAppConfig()
        .setActionCallback(
            (InAppMessage inAppMessage) -> {
                Log.i("MyApp", "Received Snapyr in-app message!");
                // trigger your own callback code here
            }))
        // Optional - change the frequency (in ms) at which Snapyr polls for new messages
        // If omitted, the default polling rate is 30000 ms, i.e. once every 30 seconds
        .setPollingRate(5000)
.build();

Fetching/Receiving In-App Messages

When you have in-app messaging enabled, the SDK handles fetching/receiving of in-app messages automatically. There are two ways in which the SDK can receive messages:

  1. Whenever your track or identify events are flushed to the back end, if this triggers any Snapyr campaigns that generate an in-app message for the current user, they will be returned by the back end and trigger in the SDK immediately.
  2. The SDK will also check the back end for any queued-up messages when it first begins, and then start polling the back end for new messages every 30 seconds, or at an interval that you specify in your config.

Acting on a custom InAppMessage

By calling .setActionCallback(InAppCallback callback), you can provide your own code that will be triggered whenever a custom in-app message arrives. You can provide either a lambda function which receives an InAppMessage object, or an instance of Snapyr’s InAppCallback class. This is a class containing a single method, onAction(InAppMessage message).

The InAppMessage Class

Content InAppContent The content of the in-app message. This is defined in the Snapyr UI when setting up the campaign that triggered this message, and typically contains the custom data you'll want to reference in your callback code. See the next section for more details on InAppContent.
Timestamp Date The datetime when the message was originally sent or scheduled from the back end
ActionType InAppActionType An enum, either ACTION_TYPE_CUSTOM, for a message that triggers your callback code, or ACTION_TYPE_OVERLAY, for a message that Snapyr automatically displays.
ActionToken String A unique token for this message, which is used for tracking KPIs such as impressions for this message.
UserID String The user ID that this message was sent to. This should generally be the same as the user ID that your current user is identified with. But in the event that your user has changed accounts, you may want to check that the UserID on the message matches your current user ID before acting on the message.

The InAppContent Class

getType() InAppContentType An enum, either CONTENT_TYPE_JSON or CONTENT_TYPE_HTML, as specified on the message and campaign in the Snapyr UI.
getJsonContent() ValueMap The content of a JSON message, as a `ValueMap` (a basic `Map` implementation).
NOTE: only valid if the content type for this message is CONTENT_TYPE_JSON.
getHtmlContent() String The content of an HTML message, as a String.
NOTE: only valid if the content type for this message is CONTENT_TYPE_HTML.

Tracking Analytics for In-App Messages

Snapyr lets you track user interaction metrics for your in-app messages to enable your team to measure the performance of your campaigns.

Automatic tracking with HTML Overlay messages

If you use an HTML overlay message, the Snapyr SDK automatically manages the entire message lifecycle - displaying, closing, and recording metrics. Metrics will be tracked as follows:

  • Impression - this metric is recorded as soon as the HTML overlay is displayed on the user’s screen.
  • Click - this metric is recorded any time a user clicks or taps one of the links or buttons within the overlay. If the click is on a link, the URL will be tracked as an additional piece of data.
  • Dismiss - if the user closes the overlay without clicking on something inside of it first, it’s recorded as a dismiss. If a user clicks a link, then later closes the overlay, it is not tracked as a dismiss.

Manual tracking for custom messages

For custom in-app messages, your code has full control over how, and whether, it displays content to the user. The Snapyr SDK can’t measure analytics automatically for custom code. Instead it provides a set of tracking functions that you can call from your code at the appropriate time. These calls cover the same set of metrics as those of HTML overlay messages.

Every incoming in-app message includes an ActionToken parameter, which is a unique string for the message. You’ll need to pass this value back to the tracking calls, which allows Snapyr to automatically connect metrics back to the source message and campaign.

Impression: trackInAppMessageImpression(final @NonNull String actionToken) Call immediately after you've presented a message to the user.
Click: trackInAppMessageClick(final @NonNull String actionToken) Call when a user clicks on, or otherwise has a positive engagement with, the message. Use this method if you don't have any additional metadata to record for this click.
Click: trackInAppMessageClick(final @NonNull String actionToken, final @NonNull Properties properties) Call when a user clicks on, or otherwise has a positive engagement with, the message. Use this method if you have additional data to record for this click, which you can include as a map of Properties. For example, you might include the url for a link that was clicked.
Dismiss: trackInAppMessageDismiss(final @NonNull String actionToken) Call if your user dismisses the message without first performing any clicks or other positive engagement.

Push Notification Calls

Snapyr makes it easy to trigger and track push notifications on Android.

Setting Up Push Notifications - Firebase

In order for push notifications on Android to work, you will need to setup your Firebase Server Key.

  1. Create a Firebase project, if you don’t have one. Go to Firebase and click ‘Create a Project’ or ‘Add Project’ and follow all directions, until you ‘Create Project’.

  2. Tie your Firebase project to your Android / Google Play app. In the center of the project overview page, click the Android icon or Add app to launch the setup for Adding firebse to your Android app. Enter your package name in the ‘Android package name’ field (get this name from Google Play console). You cankeep the ‘Debug signing certificate’ field empty. Then click ‘Register app’.

  3. Click ‘Download google-services.json’ to grab your Firebase Android Config file. It will be named google-services.json.

  4. Click the gear icon and choose ‘Project Settings’ and then choose the ‘Cloud Messaging’ tab. There should be a Server Key and Sender ID there. If not you may need to tap ‘Add server key’.

  5. You will need to paste the Firebase Server Key value and Firebase Sender ID value to the Snapyr platform while onboarding. See the Onboarding Documentation for more information.

Setting Up Push Notifications - Your Android App

  1. Add the google-services.json file to your project’s root app folder. This has all the URLs that let your app talk to Firebase.

  2. In the code that initializes the Snapyr SDK, be sure to call .enableSnapyrPushHandling(). See above for more information about initialization.

     // Create a Snapyr client with the given Android app context and Snapyr write key.
     Snapyr snapyr = new Snapyr.Builder(context, APP_WRITE_KEY)
     ... // other config options here...
     .enableSnapyrPushHandling() // add this line to enable push handling
     .build();
    
  3. Add the following to your application’s AndroidManifest.xml, as a child of <application>:

     <!-- Used by Snapyr to automatically track notification receipt/interaction -->
     <activity android:name="com.snapyr.sdk.notifications.SnapyrNotificationListener"
         android:exported="false">
         <intent-filter>
             <action android:name="com.snapyr.sdk.notifications.TRACK_BROADCAST" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>
    
     <!-- Main Snapyr push notification service - renders notifications -->
     <service
         android:name="com.snapyr.sdk.notifications.SnapyrFirebaseMessagingService"
         android:exported="false">
         <intent-filter>
             <action android:name="com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
     </service>
    
  4. Make sure to add the Network state permission to your application’s AndroidManifest.xml, after the <application> section:

     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
  5. Add the following to your module (top) level Gradle file (build.gradle):

     dependencies {
         classpath 'com.google.gms:google-services:4.3.3'
     }
    
  6. Add the following to your app level Gradle file (app/build.gradle):

     dependencies {
         implementation platform('com.google.firebase:firebase-bom:27.1.0')
         implementation('com.google.firebase:firebase-messaging')
     }
     // Add to the bottom of the file
     apply plugin: 'com.google.gms.google-services'
    

Running the Android Sample App

A sample app is included with the SDK project:

A java project is called snapyr-android-sdk/snapyr-samples/sample.

And a Kotlin project is called snapyr-android-sdk/snapyr-samples/kotlin-sample.

Import/Open the snapyr-android-sdk project in Android Studio and you should have the snapyr-samples.kotlin-sample run configuration configured. Just pick it and run the sample app inside the emulator or attached device.

Enjoy!