Last modified June 3, 2016 by Shelly Wolfe

Android

Swrve is a single integrated platform delivering everything you need to drive mobile engagement and create valuable consumer relationships on mobile. The Swrve native Android SDK enables your app to use all of these features. This guide contains all the information you need to integrate the Swrve SDK into your app.
With the release of Swrve’s Android SDK version 5.0, we have made major changes to the SDK methods and APIs. The code examples in this guide refer exclusively to version 5.0+.

Requirements

  • The Swrve Android SDK supports Android 4.0 and later (API level 14 and above) but is able to handle older versions with an empty SDK that does nothing.
  • OTT – If you are compiling your app for Android TV or Amazon Fire TV, there are no additional integration steps, however you must set the Android SDK to API level 21 (the minimum required to run Android TV). For more information on the features and campaign types supported in each OTT platform, see the OTT landing page.
  • Gradle is distributed with the SDK and used to build the SDK and its dependencies.
  • Ensure you have the latest version of Android Studio.
  • As Google have deprecated Google Cloud Messaging (GCM), we recommend upgrading to Firebase Cloud Messaging (FCM).
  • The App ID and API Key for your app. This information is available in Swrve on the Integration Settings screen (on the Setup menu, click Integration Settings).

Installing the SDK

Swrve has an open source SDK repository. There are two options for downloading the latest public Swrve Android SDK:

  • Install the Android SDK libraries using Gradle from the Swrve repository on Jcenter.
  • Download the SDK from the GitHub public repository.

Install Using Gradle

To install the Android SDK library in your project, add the following code to your build.gradle file.

Step 1: Add the Swrve repository.

Step 2: Choose a Swrve library to install, ensuring you include the latest SDK version number (for example, 5.2.0).

Basic Android SDK

Google-flavored SDK – select if you’re using any Google Play services, such as GCM or IAP

Firebase-flavored SDK – select if you’re using any Firebase services, such as FCM or IAP

Amazon-flavored SDK – select if you’re using Amazon Device Messaging (ADM)

If you’re moving from an earlier version of the Android SDK to the current version, see the Android SDK Upgrade Guide for upgrade instructions.

Amazon SDK Dependency

If you’re compiling the Amazon-flavored SDK for Android from source, it is necessary to also download the Amazon SDK from the Amazon Developer portal to get the ADM jar support file (amazon-device-messaging-1.0.1.jar). Add the ADM jar file to your project in the appropriate folder. If you are using the Swrve Gradle build configurations, the location is ./SwrveSDK/providedLibs/.

The corresponding project build.gradle files refer to the jar file using the “provided” directive that when combined with the Amazon flavor SDK, becomes amazonProvided as follows:

The providing directive tells the library or plugin to compile against the jar but not include the class implementations. They are simply stub implementations and will fail if actually executed. The runtimes exist on the Amazon device.

Debug applications (apk) built using Gradle and being built from source may also need to make use of the amazonProvided directive pointing to the adm jar in their own build.gradle dependency section. This isn’t required for release.

Basic Integration

After you have installed the SDK, complete the following for a basic integration.

Depending on your data requirements, Swrve stores all customer data and content in either our US or EU data centers. If you require EU data storage, include the EU stack information in the example below to configure the SDK to point to Swrve’s EU-based URL endpoints. If you have any questions or need assistance configuring the SDK for EU data storage, please contact support@swrve.com.

To integrate the SDK, create an instance on your application level. Replace <app_id> and <api_key> with your app ID and API key.

With the release of Swrve’s Android SDK version 5.0, we have made major changes to the APIs to ensure internal consistency and improve SDK integration. For a full list of the APIs that have changed or been deprecated, see the Android SDK 5.0 Upgrade Guide.

Minimum Android API Level

The minimum API level that the Swrve SDK supports is level 14 (Ice Cream Sandwich). If your app supports below level 14, the Swrve SDK will not track or execute on those earlier versions, but will operate as normal on level 14 and above.

If you are compiling your app for Android TV or Amazon Fire TV, you must set the Android API level to 21 (the minimum required to run Android TV).

If your app supports API levels below 14, you need to override the Swrve library defaults. Include the following overrides in your AndroidManifest.xml:

Basic integration of the Swrve SDK enables you to track important metrics and run in-app message and Conversations campaigns. To make use of additional Swrve features, such as push notifications and advanced metrics tracking, see the following sections as required.

In-App Messages and Conversations

Swrve’s in-app messages and Conversations campaigns are available as soon as you complete the basic integration described above. These features enable you to send personalized messages to your app users while they’re using your app. For more information, see Intro to In-App Messages and Intro to Conversations.

Conversations are currently not supported on OTT platforms.

To test in-app messages or Conversations in your app, you need to first create the campaign in Swrve. For more information, see Creating In-App Messages and Creating Conversations.

In-App Message and Conversation Deeplinks

When creating in-app messages and Conversations in Swrve, you can configure message buttons to direct users to perform a custom action when clicked. For example, you might configure a button to direct the app user straight to the app store to provide a rating.

Swrve’s default behavior for in-app messages and conversations is to treat custom actions as URIs. If your app has an existing custom URL scheme defined in your AndroidManifest.xml, you can use this to deeplink in your app.

In-App Message Custom Actions

For conversations, deeplinks strings are always handled as URLs. For in-app messages, it is also possible to override this behavior of treating custom actions as URL deeplinks and integrate custom actions to direct users to a sale, website or other target when they click an in-app message. Use the following callback:

For example, to send Swrve events using custom actions, add a customButtonCallback like this:

Loading Campaign Resources and Cache in the Background

The Android SDK lets you decide if you want to wait on the previous in-app messaging campaign and resources when initializing. This allows you to obtain the previous values after calling init. In some instances, this can increase the time it takes for the Swrve SDK to initialize.

You can disable this behavior and load the cache in the background by setting the following property in your configuration object:


Push Notifications

Swrve’s push notification campaigns enable you to send personalized messages to your app users while they’re outside of your app or to send silent background app updates. For more information, see Intro to Push Notifications.

Push notification campaigns are not currently supported on OTT platforms.

Push notifications are disabled by default. To enable push notifications, use either the Google- or Amazon-flavored SDK.

If this is the first push notification integration for your app, complete the following steps. If you already use other push notification providers, proceed to the If You Already Use Push Notifications section.

Step 1: Make the following changes to your AndroidManifest.xml to include the GCM, FCM or ADM receiver, Swrve’s intent service, permissions and configuration metadata.

Google

Replace ${packageName} with the main package of your app if you are not using Gradle or using an old version.

Step 2: Provide the sender ID (the project number obtained from the Google Developer Console) to the SDK on initialization. If you haven’t specified any special configuration, do the following:

If you initialized the SDK with advanced configuration, add the following line to your initialization:

For more information about the sender ID, see How Do I Manage the Server Key for Push Notifications?

Firebase

Replace ${packageName} with the main package of your app if you are not using Gradle or using an old version.

Step 2: Add the following script dependency:

Step 3: Add the following plugin to your app. Replace X.X.X with the FIREBASE_TOOLS_VERSION that the SDK currently uses. For more information, see the SDK gradle.properties file on GitHub.

Step 4: Add the google-services.json from the Firebase Console to your project. For more information, see the Firebase help article, Download a configuration file.

Amazon

Notes:

  • The maximum Android API Level is 15 for Amazon Fire devices. For more information, see Amazon Device Messaging.
  • Add the the Amazon namespace xmlns:amazon=”http://schemas.amazon.com/apk/res/android to your <manifest>.

Step 2: If you do your own application signing, you need to add the Amazon api_key.txt to the assets folder of your project. To get this key from Amazon, follow this guide on Obtaining Amazon Device Messaging Credentials.

Android O Notification Channels

With Android O, Google has introduced the concept of notifications channels. In order to receive pushes on a device running Android O, you must define a notification channel in your config.

If You Already Use Push Notifications

Step 1: To make sure other providers continue to work, move Swrve’s intent service to the bottom of your application definition. This prevents the broadcast listener from calling it as the first option.

Step 2: Create a custom broadcast listener and use it to replace the base GcmReceiver. This broadcast listener will make sure to call Swrve when push notifications are directed to it.

For examples of how to create the custom broadcast listener, see one of the following samples in GitHub:

Step 3: Similarly, update your AndroidManifest.xml like the example in the sample.

Note that you must replace ${packageName} with the main package of your app if you are not using Gradle or using an old version.

Step 4: Provide the sender ID (the project number obtained from the Google Developer Console) when creating the SDK instance. If you haven’t specified any special configuration, do the following:

For more information about the sender ID, see How Do I Manage the Server Key for Push Notifications?

If you initialized the SDK with advanced configuration, add the following line to your initialization:

Configuring Silent Notifications

To enable silent push notifications in your app, add the new silent push listener in your Application’s onCreate activity:

The purpose of a silent notification is to deliver data to your app in the background, such as a content update. You should never call the SDK from a silent notification.

Note: This listener is executed from the push service.

Creating and Entering the Android Server Key

To enable your app to send push notifications to Google Play devices, you require a server key. For more information, see How Do I Manage the Server Key for Push Notifications?

Enabling Amazon Device Messaging

To enable ADM in your Amazon app, log in to the Amazon Developer portal, go to Apps & Services > My App > Device Messaging and click Enable.

Creating and Entering the Amazon Client ID and Client Secret

To enable your app to send push notifications to Amazon devices, you need the Client ID and Client Secret for your app. For information on how to get these credentials, see Obtaining Amazon Device Messaging Credentials.

Generally, you enter the Client Id and Client Secret on the Swrve dashboard when configuring the Integration Settings as part of the Swrve onboarding process. You can edit the settings on this screen later on if required.

Step 1: On the Setup menu, click Integration Settings.

Step 2: Under the Push Notifications section, in the Amazon Device Messaging Service section, enter your Client Id and Client secret.

Step 3: Test the server key by sending a test push notification to one of your QA devices. To send a test push notification:

  • Select your QA device from the list of available devices.
  • Click Send Test Push.

Advanced Configuration

This section describes how to configure advanced options for Android SDK push notification integration. For a demo of advanced push notifications, see the Swrve SDK Advanced Push Notifications Sample in GitHub.

Processing Custom Payloads

To process notifications when they are opened from a push notification, add a listener for push notifications to the SDK before initialization in your Application class:

Using Custom Sounds

You can send push notifications with custom sounds. To do so, place your custom sound under res/raw and set your sounds in the Swrve service. For more information about adding custom sounds in Swrve, see Intro to Push Notifications.


Sending Events

The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom events. (For a list of default Swrve events, see About Audience Filters, Events.) In turn, you can use app-generated events to trigger in-app messages, while both app- and server-generated events help you define segments and perform in-depth analysis.

Custom Events

To send a custom event, include the below example in a method where you want to send an event to Swrve.

Requirements for sending custom events:

  • Do not send the same named event with different case. For example, if you send tutorial.start, then ensure you never send Tutorial.Start.
  • Use a period (.) in your event names to organize their layout in the Swrve dashboard. Each ‘.’ creates a new branch in the Event name column of the Events report, and groups your events so they are easy to locate.
  • Do not send more than 1000 unique named events.
    • Do not add unique identifiers to event names. For example, Tutorial.Start.ServerID-ABDCEFG
    • Do not add timestamps to event names. For example, Tutorial.Start.1454458885
  • Do not use the swrve.* or Swrve.* namespace for your own events. This is reserved for Swrve use only. Custom event names beginning with Swrve. are restricted and cannot be sent.

Event Payloads

You can add and send an event payload with every event. This allows for more detailed reporting around events and funnels.

Notes on associated payloads:

  • The associated payload should be a dictionary of key/value pairs; it is restricted to string and integer keys and values.
  • There is a maximum cardinality of 500 key-value pairs for this payload per event. This parameter is optional, but only the first 500 payloads are displayed in the dashboard. The data is still available in raw event logs and for audience filtering.
  • It is not currently possible to use payloads as triggers for push notifications. Use events for these purposes.
  • If you want to use event payloads to target your campaign audiences, you can configure up to 10 custom events with a maximum of 10 payloads per event for audience filtering purposes. For more information, see Targeting your audience by event payloads.

For example, if you want to track when a user starts the tutorial experience, it might make sense to send an event named tutorial.start and add a payload time that captures how much time it took the user to complete the tutorial.

Custom User Properties

The Swrve SDK sends certain user properties by default and also enables you to assign custom properties to update the user’s status. (For a full list of the default user properties, see Assigning User Properties.)

For example, you could create a custom user property called premium, and then target non-premium users and premium users in your campaigns.

When configuring custom properties for Android, the Swrve SDK only supports string values.

Example of group of user properties

Example of single date-typed user property

Use the Date object to send a DateTime user property; for example, the current date at the time of a user purchase:

Virtual Economy Events

To ensure virtual currency events are not ignored by the server, make sure the currency name configured in your app matches exactly the Currency Name you enter in the App Currencies section on the App Settings screen (including case-sensitive). If there is any difference, or if you haven’t added the currency in Swrve, the server will ignore the event and return an error event called Swrve.error.invalid_currency. Additionally, the ignored events are not included in your KPI reports. For more information, see Add Your App.

If your app has a virtual economy, send the purchase event when users purchase in-app items with virtual currency.

Send the currency given event when you give users virtual currency. Examples include initial currency balances, retention bonuses and level-complete rewards.

In-App Purchase Events and Validation

If your app has in-app purchases (IAPs), send the IAP event when a user purchases something with real money. This section details the IAP functions for unverified IAP events and for IAP events where the receipt can be verified. It also details how to enable IAP receipt validation for Google Play.

IAP Functions

In the case of Android platforms (both native and Unity), Swrve does not automatically receive IAP receipts. For Swrve to verify IAPs, you must send an event for each purchase using the IAP API with the purchase receipt. For native Android, use Google Play services for this purpose. For Unity Android, you must use a Unity plugin to receive IAP receipts.

IAP functions for unverified IAP events (that is, for any app store other than Google Play):

IAP functions for IAP events where the receipt can be verified (for now, only Google Play is supported):

Example:

The following code is the initialization of the in-app purchase:

The following code is the callback function (executed when the purchase has been made):

It is also possible to create a SwrveIAPRewards object containing all the in-app currency and bundle items purchased (if the purchase contained other in-app items):

In this instance, iapPlay can be supplied with this object:

Enabling IAP Receipt Validation

To enable validation of Google Play IAP receipts, on the Integration Settings screen, in the IAP Validation section, in the Google Play Licensing Public Key field, you must enter and save the public key for licensing and in-app billing. This public key is used to verify digital signatures. Google signs data (the app itself for verifying that the app has been payed for or the in-app purchase receipt) and Swrve then uses the public key to verify every purchase before calculating your revenue KPIs. This ensures that your revenue figures are as accurate as possible (ignoring pirates and cheaters).

You usually enter the public key into Swrve when configuring the Integration Settings screen as part of the Swrve onboarding process. You can edit the settings on this screen at any time, as required. On the Setup menu, click Integration Settings.

To access your public key, access the Google Play Developer Console and navigate to All applications > [Your Application] > Services and APIs. The public key is then displayed in the Your License Key For This Application section as illustrated below. For more information, see the Google Play In-App Billing documentation.

Untitled-6.jpg

Verifying IAP Receipt Validation

Use the following events to monitor the success of IAP receipt validation:

  • swrve.valid_iap – fired if receipt verification has been successful and the receipt is valid.
  • swrve.invalid_iap – fired if receipt verification has been successful and the receipt is invalid.

Resource A/B Testing

Integrating Swrve’s resource A/B testing functionality enables you to use Swrve to test how users respond to changes to the native app content. For more information about resource A/B testing, see Intro to Resource A/B Testing.

To get the latest version of a resource from Swrve using the Resource Manager, use the following:

If you want to be notified whenever resources change, you can add a callback function as follows:


Testing Your Integration

After you’ve completed the above, the next step is to test the integration. For more information, see Testing Your Integration.


Upgrade Instructions

If you’re moving from an earlier version of the Android SDK to the current version, see the Android SDK Upgrade Guide for upgrade instructions.


SDK Samples

For a general demo of the Swrve Android SDK, see the Swrve Android SDK samples on GitHub.