/android-sdk

Infinario Android SDK

Primary LanguageJavaApache License 2.0Apache-2.0

Infinario Android SDK

Infinario Android SDK is available in this Git repository: https://github.com/infinario/android-sdk.

Installation (Android Studio / Gradle)

  1. Download the latest release of the Android SDK
  2. Unzip / untar the downloaded SDK into a preferred directory
  3. In Android Studio, click File -> New -> Import Module... or in older version click File -> Import Module...
  4. In the opened dialog window, locate the unzipped Android SDK directory and click Finish
  5. In Android Studio, click File -> Project Structure...
  6. In the opened dialog click on your app (on the left side) and open Dependencies tab
  7. Click on the Plus sign in the upper right corner and select Module dependency
  8. Select :infinario-android-sdk-x.x.x and click OK and then click again OK
After completing the steps above the Infinario Android SDK is now included in your app and ready to be used.

Usage

Basic Interface

Once the IDE is set up, you may start using the Infinario library in your code. First you need to you need to know the URI of your Infinario API instance, usually https://api.infinario.com and your projectToken (Overview page in the web application). To interact with the Infinario SDK, you need to obtain an instance of the Infinario class using the application's context and projectToken (the URI parameter is optional):
// Use public Infinario instance
Infinario infinario = Infinario.getInstance(getApplicationContext(), projectToken);

// Use custom Infinario instance Infinario infinario = Infinario.getInstance(getApplicationContext(), projectToken, "http://url.to.your.instance.com");

To start tracking, you need to identify the customer with their unique customerId. The unique customerId can either be a String, or an Map representing the customerIds as referenced in the API guide. Setting

String customerId = "123-foo-bar"

is equivalent to

Map<String, String> customerId = new HashMap<> ();
customerId.put("registered", "123-foo-bar");

In order to identify a customer, call the identify() method on the obtained Infinario instance as follows:

// Identify a customer with their customerId
infinario.identify(customerId);

The identification is performed asynchronously and there is no need to wait for it to finish. All tracked events are stored in the internal SQL database until they are sent to the Infinario API.

You may track any event by calling the track() method on the Infinario instance. The track() method takes one mandatory and two optional arguments. First argument is String type which categorizes your event. This argument is required. You may choose any string you like.

Next two arguments are Map<String, Object> properties and Long timestamp. Properties is a map which uses String keys and the value may be any Object which is serializable by org.json.JSONObject class. Properties can be used to attach any additional data to the event. Timestamp is in milliseconds since 1970-01-01 00:00:00 GMT and it can be used to mark the time of the event's occurence. The default timestamp is preset to the time of the tracking of the event.

Map<String, Object> properties = new HashMap<>();
properties.put("item_id", 45);
Long timestamp = System.currentTimeMillis();

// Tracking of buying an item with item's properties at a specific time
track("item_bought", properties, timestamp);

// Tracking of buying an item at a specific time
track("item_bought", timestamp);

// Tracking of buying an item with item's properties
track("item_bought", properties);

// Basic tracking that an item has been bought
track("item_bought");

The Infinario Android SDK provides you with means to store arbitrary data that is not event-specific (e.g. customer's age, gender, initial referrer). Such data is tied directly to the customer as their properties. The update() method is used to store such data:

Map<String, Object> properties = HashMap<> ();
properties.put("age", 34);

// Store customer's age
infinario.update(properties);

Automatic events

INFINARIO Android SDK automatically tracks some events on its own. Automatic events ensure that basic user data gets tracked with as little effort as just including the SDK into your game. Automatic events include sessions, installation, identification and payments tracking.

Sessions

Session is a real time spent in the game, it starts when the game is launched and ends when the game goes to background. But if the player returns to game in 60 seconds (To change TIMEOUT value, call setSessionTimeOut), game will continue in current session. Tracking of sessions produces two events, session_start and session_end. To track session start call trackSessionStart() from where whole game gets focus (e.g. onStart method) and to track session end call trackSessionEnd() from where whole game loses focus (e.g. onStop method). If you have more activities, put them to all activities you have.

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

    infinario = Infinario.getInstance(getApplicationContext(), "projectToken");
}

@Override
protected void onStart(){
    super.onStart();

    infinario.trackSessionStart();

    /* or with properties

    Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();
    properties.put("item_id", 45);

    infinario.trackSessionStart(properties);
    */
}

@Override
protected void onStop(){
    super.onStop();

    infinario.trackSessionEnd();

    /* or with properties

    Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();
    properties.put("item_id", 45);

    infinario.trackSessionEnd(properties);
    */
}

Both events contain the timestamp of the occurence together with basic attributes about the device (OS, OS version, SDK, SDK version and device model). Event session_end contains also the duration of the session in seconds. Example of session_end event attributes in JSON format:

{
  "duration": 125,
  "device_model": "LGE Nexus 5",
  "device_type": "mobile",
  "ip": "10.0.1.58",
  "os_name": "Android",
  "os_version": "5.0.1",
  "sdk": "AndroidSDK",
  "sdk_version": "1.1.4"
  "app_version": "1.0.0"
}

Installation

Installation event is fired only once for the whole lifetime of the game on one device when the game is launched for the first time. Besides the basic information about the device (OS, OS version, SDK, SDK version and device model), it also contains additional attribute called campaign_id which identifies the source of the installation. For more information about this topic, please refer to the aquisition documentation. Please note that com.android.vending.INSTALL_REFERRER intent is used to acquire the source of the installation. Example of installation event:

{
  "campaign_name": "Advertisement on my website",
  "campaign_id": "ui9fj4i93jf9083094fj9043",
  "link": "https://play.google.com/store/...",
  "device_model": "LGE Nexus 5",
  "device_type": "mobile",
  "ip": "10.0.1.58",
  "os_name": "Android",
  "os_version": "5.0.1",
  "sdk": "AndroidSDK",
  "sdk_version": "1.1.4"
}

Identification

Identification event is tracked each time the identify() method is called. It contains all basic information regarding the device (OS, OS version, SDK, SDK version and device model) as well as registered attribute which identifies the player. Example of an identification event:

{
  "registered": "player@email.com",
  "device_model": "LGE Nexus 5",
  "device_type": "mobile",
  "ip": "10.0.1.58",
  "os_name": "Android",
  "os_version": "5.0.1",
  "sdk": "AndroidSDK",
  "sdk_version": "1.1.4"
}

Payments for Google Play Store

In order to use the automatic payment tracking, the INFINARIO Android SDK needs to know when a purchase flow has finished. After the player goes through the whole purchase process, Android calls onActivityResult method on the activity which started the purchase flow. That is the place in the game code where INFINARIO Android SDK instance needs to get notified about the purchase using the trackGooglePurchases(int, Intent) method. For more details, please refer to the sample code below:

// override this method in each activity which starts the purchase flow
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // first check if the infinario instance has been initialized
    if (infinario != null) {
        // pass resultCode and the intent, INFINARIO Android SDK automatically
        // determines whether this is a purchase intent or not
        infinario.trackGooglePurchases(resultCode, data);
    }
}

Payments for Amazon Store

Implementation is made by 2 steps.

First, you must get product's information by call method loadAmazonProduct(JSONObject amazonJsonProductDataResponse) from Amazon SDK Purchase Listener onProductDataResponse(final ProductDataResponse response).

@Override
public void onProductDataResponse(final ProductDataResponse response) {
    final ProductDataResponse.RequestStatus status = response.getRequestStatus();

    switch (status) {
        case SUCCESSFUL:
            final Set unavailableSkus = response.getUnavailableSkus();
            try {
                infinario.loadAmazonProduct(response.toJSON());
            } catch (JSONException e) {
            }
            iapManager.enablePurchaseForSkus(response.getProductData());
            iapManager.disablePurchaseForSkus(response.getUnavailableSkus());
            break;
        case FAILED:
        ......

Second, call method trackPurchases(JSONObject amazonJsonPurchaseResponse) in Amazon SDK Purchase Listener onPurchaseResponse(final PurchaseResponse response) to track Amazon purchases.

@Override
public void onPurchaseResponse(final PurchaseResponse response) {
    final PurchaseResponse.RequestStatus status = response.getRequestStatus();

    switch (status) {
        case SUCCESSFUL:
            final Receipt receipt = response.getReceipt();
            try {
                infinario.trackAmazonPurchases(response.toJSON());
            } catch (JSONException e) {
            }
            iapManager.setAmazonUserId(response.getUserData().getUserId(), response.getUserData().getMarketplace());
            iapManager.handleReceipt(receipt, response.getUserData());
            iapManager.refreshOranges();
            break;
        case ALREADY_PURCHASED:
        .....

Purchase events (called hard_purchase) contain all basic information about the device (OS, OS version, SDK, SDK version and device model) combined with additional purchase attributes brutto, currency, product_id and product_title. Brutto attribute contains price paid by the player. Attribute product_title consists of human-friendly name of the bought item (e.g. Silver sword) and product_id corresponds to the product ID for the in-app purchase as defined in your Google Play / Amazon Developer Console. Example of purchase event:

{
  "brutto": 0.911702,
  "currency": "EUR",
  "item_id": "android.test.purchased",
  "item_title": "Silver sword",
  "device_model": "LGE Nexus 5",
  "device_type": "mobile",
  "ip": "10.0.1.58",
  "os_name": "Android",
  "os_version": "5.0.1",
  "sdk": "AndroidSDK",
  "sdk_version": "1.1.4"
}

Virtual payment

If you use in your project some virtual payments (e.g. purchase with in-game gold, coins, ...), now you can track them with simple call trackVirtualPayment.

Infinario.trackVirtualPayment(String currency, int amount, String itemName, String itemType);

Segmentation

If you want to get current segment of your player, just call getCurrentSegment. You will need id of your segmentation and project secret token.

infinario.getCurrentSegment("segmentation_id", "project_secret", new SegmentListener() {
    @Override
    public void onSegmentReceive(boolean wasSuccessful, InfinarioSegment segment, String error) {
        String name = segment.getName();
    }
});

Google Push notifications

Infinario web application allows you to easily create complex scenarios which you can use to send push notifications directly to your customers. The following section explains how to enable receiving push notifications in the Infinario Andriod SDK.

For push notifications to work, you need a working Google API project. The following steps show you how to create one. If you already have created a Google API project and you have your project number (or sender ID) and Google Cloud Messaging API key, you may skip this part of the tutorial and proceed directly to enabling of the push notifications in the Infinario Android SDK.

Google API project

  1. In your preferred browser, navigate to https://console.developers.google.com/
  2. Click on Create Project button
  3. Fill in preferred project name and click Create button
  4. Please wait for the project to create, it usually takes only a few seconds
  5. After the project has been created you will be redirected to the Project Dashboard page where you'll find Project Number which is needed in the Infinario Android SDK
  6. In the left menu, navigate to APIs & auth -> APIs and find Google Cloud Messaging for Android
  7. Please make sure the Google Cloud Messaging for Android is turned ON
  8. In the left menu, navigate to APIs & auth -> Credentials and click on Create new Key button
  9. Click on Server key button and the click on Create button
  10. Copy the API key which is needed for the Infinario web application

Infinario web application

Once you have obtained Google Cloud Messaging API key, you need to enter it in the input field on the Company / Settings / Notifications in the Infinario web application.

Infinario Android SDK

By default, receiving of push notifications is disabled. You can enable them by calling the method enableGooglePushNotifications(). Please note that this method needs to be called only once. Push notifications remain enabled until the opposite method, disableGooglePushNotifications() is called. Method enableGooglePushNotifications() has one mandatory argument String senderId or Project number. The Project number can be obtained from Project Dashboard of your Google API project at https://console.developers.google.com/. enableGooglePushNotifications() has one optional argument int iconDrawable which is ID of the icon drawable which should be used as icon in the Android notification.
String senderId = "your project number";

// Enable push notifications using given icon infinario.enableGooglePushNotifications(senderId, R.drawable.icon);

Flushing events

All tracked events are stored in the internal SQL database in the Android app. By default, Infinario Android SDK automagically takes care of flushing events to the Infinario API. This feature can be turned off with method disableAutomaticFlushing() which takes no arguments. Please be careful with turning automatic flushing off because if you turn it off, you need to manually call Infinario.flush(context); to flush the tracked events manually everytime there is something to flush.