Getting started with Android SDK

Detailed technical documentation on Mars Android SDK using Android Studio to track events from your Android device and to run different incentive programs

What is the Mars Android SDK?

The Mars Android SDK allows you to

  1. Track event data from your app. It can be easily integrated into your Android application.

  2. Run Incentive programs

You can check the GitHub codebase if you want to get more hands on or keen to know the SDK architecture

SDK setup requirements

To set up the Mars Android SDK, there are a few prerequisites as mentioned below:

  • You will need to set up a Mars Account

  • Once signed up, your Android source MARS_SDK_API_KEY will appear in the Dashboard, as shown:

Mars Dashboard SDK Integration page

To use push notification as a channel, add your FCM server key above

Installing the SDK

We distribute our Android SDK through Bintray. This is the recommended way to use our SDK is through Android Gradle build system. It's the easiest way to add the SDK to your project.

To add the dependencies, perform the following steps:

  1. Open your app/build.gradle (Module: app) file, and add the following lines of code:

    repositories {
    maven {
    url "https://dl.bintray.com/marax-ai/mars-sdk-android-core"
    }
    }
  2. Add the dependency under dependencies as shown:

    implementation 'ai.mars.android.sdk:mars-sdk-core:0.1.4'
    // add the follwing line if you don't have Gson included already
    implementation 'com.google.code.gson:gson:2.8.6'

Initializing the Mars client

Add the following code to the onCreate method in your Application class:

Don't have an Application class? Follow our Add an Application Class to Your Android Application guide to add one.

JAVA
JAVA
MarsClient marsClient = MarsClient.getInstance(
this,
"MARS_SDK_API_KEY",
new MarsConfig.Builder()
.withLogLevel(MarsLogger.MarsLogLevel.DEBUG)
.withTrackLifecycleEvents(true)
.withRecordScreenViews(true)
.build()
);

We automatically track the following optional events:

  1. Application Installed

  2. Application Updated

  3. Application Opened

  4. Application Backgrounded

You can disable these events using the withTrackLifecycleEvents method and passing false. But it is highly recommended to keep them enabled.

Setting the Android permission

Add this line to your AndroidManifest.xml file of your application for internet permission:

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

Push Notification Support via Firebase

If you are using push notification as outbound channel, you need to configure your firebase service to allow Mars SDK to use refreshed tokens

In your FirebaseMessagingService Override onNewToken

@Override
public void onNewToken(String token) {
marsClient.registerDevice(token, FirebaseInstanceId.getInstance().getId());
// Add the above line
...
}

For Mars to add push notification you have to add your Firebase server key on the dashboard

In-App Notification Support

If you are running campaigns with In App nudges, you need to configure your firebase service to allow Mars SDK to capture messages

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
marsClient.captureMessage(remoteMessage);
// Add the above line
}

Mars Offers and Incentive Programs

Mars SDK provides inbuilt functionality to display incentive programs and all the offers from mars campaigns with a webview.

An example of this implementation is as shown:

Button showAllMaraxOffersButton = findViewById(R.id.maraxAllOffersButton);
showAllMaraxOffersButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WebView myWebView = marsClient.drawOfferView(YourActivity.this);
setContentView(myWebView);
}
});

An sample view is as shown

Building/ Integrating with your own offers view

If you have native offers view and wants to add mars offers and rewards on your native view, the data can be retrieved as shown:

MarsReward[] marsRewards = marsClient.getMarsRewards();

Key

Type

Desc

id

String

Reward ID

title

String

Title of the reward

body

String

Body of reward

type

String

no-promo/promo

ui

String

scratch-card, coupon, spinwheel etc

updatedAt

String

expiry

String

promocode

String

handledBy

String

Processing of the reward is handle by marax/client

Applying offers and order validation

In order to apply or validate any offers, send details of your order as MarsOrder

// Create a reward Object
MarsReward reward = new MarsReward("a123", null, null, "monetory", "scratch-card", null, "FLAT20", "marax");
// Create a order object
MarsOrder order = new MarsOrder(new ArrayList<MarsOrder.Product>(), new ArrayList<MarsOrder.Fulfillment>(), new MarsOrder.CartValue(123,"rupees"), new MarsOrder.OrderValue(100,"rupees"), "card", new MarsOrder.TotalDiscount(10, "monetory" ), new MarsOrder.FinalPrice(300, "rupees" ), reward);
// Process the order updation
MarsProcessedOrder processedOrder = getMarsClient().processOrderUpdate(order);
// Access the information required from the processedOrder like so
MarsOrder updatedOrder = processedOrder.getOrder()
String orderToken = processedOrder.getToken()
String orderProcessingError = processedOrder.getError()
// Access required data from updatedOrder
MarsOrder.CartValue cv = updatedOrder.getCartValue();

See here, to get more info on the Mars Order structure

Track

You can record the users' activity through the track method. Every action performed by the user is called an event.

An example of the track event is as shown:

JAVA
JAVA
Map<String,Object> properties = new HashMap<>();
properties.put("test_key_1", "test_value_1");
Map<String, String> childProperties = new HashMap<>();
childProperties.put("test_child_key_1", "test_child_value_1");
properties.put("test_key_2", childProperties);
marsClient.track(
new MarsMessageBuilder()
.setEventName("test_track_event")
.setUserId("test_user_id")
.setProperty(properties)
.build()
);

The track method can be used in two ways:

  1. Firstly, you can use TrackPropertyBuilder to create the property object and pass the MarsMessage object with property to track method.

  2. Alternatively, you can follow the method signature as below:

Name

Data Type

Required

Description

name

String

YES

Name of the event you want to track

property

MarsProperty or Map<String, Object>

NO

Extra data properties you want to send along with the event

options

MarsOption

NO

Extra event options

We have defined a set of standard events which have special meaning in our system. Check out the specifications for your application and industry.

Identify

Capture deviceId and use that as anonymousId for identifying the user. It helps to track the users across the application installation. To attach more information to the user, you can use the identify method. Once you set the identify information to the user, those will be passed to the successive track or screen calls. To reset the user identification, you can use the reset method.

An example identify event is as shown:

JAVA
JAVA
MarsTraits traits = new MarsTraits();
traits.putBirthday(new Date());
traits.putEmail("abc@123.com");
traits.putFirstName("First");
traits.putLastName("Last");
traits.putGender("m");
traits.putPhone("5555555555");
MarsTraits.Address address = new MarsTraits.Address();
address.putCity("City");
address.putCountry("USA");
traits.putAddress(address);
traits.put("boolean", Boolean.TRUE);
traits.put("integer", 50);
traits.put("float", 120.4f);
traits.put("long", 1234L);
traits.put("string", "hello");
traits.put("date", new Date(System.currentTimeMillis()));
marsClient.identify("test_user_id", traits, null);

The identify method can be used in two ways. You can use MarsTraitsBuilder to create the traits object and pass the MarsMessage object with property to the identify method.

Alternatively, you can follow the method signatures below:

Name

Data Type

Required

Description

traits

MarsTraits

YES

Traits information for the user

options

MarsOption

NO

Extra options for the identify event

OR

Name

Data Type

Required

Description

userId

String

YES

Developer identity for the user

traits

MarsTraits

NO

Traits information for user

option

MarsOption

NO

Extra options for the identify event

Screen

You can use the screen call to record whenever the user sees a screen on the mobile device. You can also send some extra properties along with this event.

An example of the screen event is as shown:

JAVA
JAVA
marsClient.screen(
"MainActivity",
"HomeScreen",
new MarsProperty().putValue("foo", "bar"),
null
);

The screen method can be used in two ways. Firstly, you can use MarsPropertyBuilder and pass property in MarsMessage, and use the screen method to track a screen view action.

Alternatively, you can use the following method signature:

Name

Data Type

Required

Description

screenName

String

YES

Name of the screen viewed.

property

MarsProperty

NO

Extra property object that you want to pass along with the screen call.

category

String

NO

Category of the screen visited, such as HomeScreen, LoginScreen. Useful for tracking multiple Fragment views under a single Activity.

option

MarsOption

NO

Extra options to be passed along with screen event.

Reset

You can use the reset method to clear the persisted traits for the identify call. This is required for Logout operations.

JAVA
JAVA
marsClient.reset();

Configuring your Mars client

You can configure your client based on the following parameters using MarsConfig.Builder:

Parameter

Type

Description

Default Value

logLevel

int

Controls how much of the log you want to see from the SDK.

MarsLogger.MarsLogLevel.NONE

endPointUri

String

URL of your data-plane. Please refer above to see how to fetch the data plane URL.

https://sdk-test.marax.ai

flushQueueSize

int

Number of events in a batch request to the server.

30

dbThresholdCount

int

Number of events to be saved in the SQLite database. Once the limit is reached, older events are deleted from the DB.

10000

sleepTimeout

int

Minimum waiting time to flush the events to the server.

10 seconds

configRefreshInterval

int

It will fetch the config from dashboard after this many hours.

2

trackLifecycleEvents

boolean

Whether SDK will capture application life cycle events automatically.

true

recordScreenViews

boolean

Whether SDK will capture screen view events automatically.

false

Debugging

If you run into any issues regarding the Mars Android SDK, you can turn on the VERBOSE or DEBUG logging to find out what the issue is. To turn on the logging, change your MarsClient initialization to the following:

Java
Java
MarsClient marsClient = MarsClient.getInstance(
this,
MARS_SDK_API_KEY,
new MarsConfig.Builder()
.withEndPointUri(YOUR_DATA_PLANE_URL)
.withLogLevel(MarsLogger.MarsLogLevel.DEBUG)
.build()
);

FAQs

What is the Android version required to set up the Mars Android SDK?

We currently support API 14: Android 4.0 (IceCreamSandwich) or higher.

I don't have an Application class to initialize my Mars client. What do I do?

Please follow our Adding an Application class to your Android Application guide to add an Application class.

How do I set the Android permissions?

Please refer to the Setting the Android Permission section above to do this.

Can I use the library with Maven?

Yes, you can use the library with maven.

<dependency>
<groupId>ai.mars.android.sdk</groupId>
<artifactId>mars-sdk-core</artifactId>
<version>0.1.4</version>
<type>pom</type>
</dependency>

Contact us

In case of any queries, you can reach out to us at engineering@marax.ai, or feel free to open an issue on our GitHub Issues page in case of any discrepancy.