Close

Android SDK

The SDK code is in the com.omniata.android.sdk package, and there are 10 classes inside of the package altogether. The SDK logs using android.util.Log. It has internal log level setting, which defaults to Log.ASSERT. The log level can be changed using setLogLevel().

Content:

Installation and upgrade

The latest available SDK can be found below:

Platform Links Version Release Date
Android Source code
API details
2.1.14 17 Nov 2016

The Omniata Android SDK requires the following permissions in your ApplicationManifest.xml:

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

Place omniata-android-sdk.jar in your project’s lib directory. Finally add an import for the SDK.

Upgrading to the latest version involves replacing the old jar with the new one. Then import the SDK package with:

import com.omniata.android.sdk.*;

Integrating Omniata Android SDK

Initialization

For initial testing it is recommended to track events in debug mode against the event monitor. This will allow you to debug your events in real-time.

Initialize the library by calling the initialize function with the identifier of the user and the API key provided in the panel. This should be called whenever the user begins their session:

public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
...
//========================
// Initialize Omniata SDK
//========================
Activity activity = this;
String apiKey = "<API_KEY>";
String userId = "<USER_ID>";
String org = "<ORG_NAME>";

// Sends events to Production API
Omniata.initialize(activity, apiKey, userId, org);

...
}
...
}

The value in <ORG_NAME> is the organization part of the URL you use to access Omniata Panel, for example in https://acme.panel.omniata.com the <ORG_NAME> value would be “acme”. The same principle applies to <USER_ID> which is your in-app user identifier and <API_KEY> which is the qualifier for the application and environment of the current build.

To send data to a customized API endpoint, here is the example of usage (the channel API endpoint will also be changed in this case):

public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
...
//========================
// Initialize Omniata SDK with Customized BaseURL
//========================
Activity activity = this;
String apiKey = "<API_KEY>";
String userId = "<USER_ID>";
String org = "<ORG_NAME>";
String baseURL = "<BASE_URL>";

// Sends events to customized Event API, the event API should be baseURL+"/event?" and the channel API should be baseURL+"/channel?"
Omniata.initialize(activity, apiKey, userId, org, baseURL);

...
}
...
}

Tracking Events

Standard events have their own build-in method for tracking. Custom events can be tracked using a generic method specified below.

Event Method When to call
Load Omniata.trackLoad(); Whenever the app starts or is brought to foreground.
Revenue Omniata.trackRevenue(total, currencyCode); For verified in-app purchases only. Three character currency code should follow ISO-4217 specifications. The Omniata SDK does not validate or verify purchases.
Advertiser Id Omniata.trackAdvertiserID(parameters); Upon first load of the application ever. When needed in case the AdId changes. See below for more details.
Custom Omniata.track("{name}", parameters); When the target action or event is detected.

To track the advertiser ID you can use the following as a template:

import org.json.JSONObject;
import org.json.JSONException;
...
JSONObject parameters = new JSONObject();
try {
     parameters.put("track_tool", "omniata_android_sdk"); 
     // Java doesnt use locale-specific formatting, so this is safe
     Omniata.trackAdvertiserID(parameters);
} catch (JSONException e) {
     e.printStackTrace();
}

To register custom events parameters use for example:

import org.json.JSONObject;
import org.json.JSONException;
...
JSONObject parameters = new JSONObject();
try{
     parameters.put("xp", 1000);
     parameters.put("level", 2);
} catch(JSONException e){
     // do something
}

Then call the tracking method as

Omniata.track("level_up", parameters);

The Android SDK automatically adds event parameters in the trackLoad method. These parameters are used for segmentation and reporting. Below is a list of the added parameters.

Parameter Name Details
om_device The device model, taken from android.os.Build.MODEL.
om_platform The platform name, in this case “android”.
om_os_version Version of the operating system, in Android SDK obtained using SystemInfo.operatingSystem;.
om_sdk_version Version of the SDK.
om_android_id Corresponds to Settings.Secure.ANDROID_ID.
om_android_serial Serial number of device android.os.Build.SERIAL.
om_android_device Device name android.os.Build.DEVICE.
om_android_hardware Hardware details android.os.Build.HARDWARE.
om_package_version_code App version as taken from getPackageManager().getPackageInfo(getPackageName(),0).versionCode.
om_package_version_name App version name as taken from getPackageManager().getPackageInfo(getPackageName(),0).versionName.
om_delta Time difference (seconds) between when the event was created and when it was was sent. Added in all events.

When the application code asks the SDK to send an event, the event is not immediately sent, instead the event is added to a in-memory queue. A lock is obtained for a very short time while adding. There is a background thread that periodically (every few seconds) polls the persistent storage for events. If there is an event, and network is reachable, the event is sent.

The persistent storage is located a SQLite database table events. The SDK uses the following code to determine the network reachability:

ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();

A retry mechanism is used for event sending. In the case of event sending fails, the sending system sleeps a certain time and retries. In retried events there is an event parameter om_retry having the value of the number of retries made so far. Sleep time between retries is doubled for each attempt, and reset upon success. The minimum sleep time is one second, i.e. max one event per second is sent. The max sleep is around one minute.

Requesting Content

A Channel API request is made by calling the Omniata.channel() method, which is non-blocking. In case the call to the Channel API responds successfully the response is a JSON payload. The onSuccessmethod of the OmniataChannelResponseHandler can be called to retrieve the response content. Correspondingly, in case of HTTP-level issues or invalid JSON the onError method is called. In both cases activity.runOnUiThread is used to wrap the call.

Channel message can be retrieved from mChannel.channelMessage, but it can only be retrieved after the loading finishes, otherwise it will cause null pointer exception. Here is an example method call:

int channel_id = 40;
OmniataChannelEngine mChannel = new OmniataChannelEngine();
//Load the channel message for certain channel
Omniata.channel(channel_id, mChannel);

Working With Push Notifications

This section covers the client side implementation to enable or disable push notifications. You can find details for configuring your application to allow Omniata to send push notifications to your App in the Setup Push Notifications guide.

In order to enable push notification, you need to request a device token that will enable the apple servers to identify the device.

To register a device to receive push notifications you can use:

//Send push token directly
String token = "<GCM Registration ID>"
Omniata.enablePushNotifications(token);

To disable a user from receiving push notifications, you can use the method disablePushNotifications.

//Disable push notification
Omniata.disablePushNotifications();

When enable tracking of received notifications, the first step is to pass the content of the android GCM in the intent (here we store it in OmniataGCM):

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("OmniataGCM", data);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_stat_ic_notification)
        .setContentTitle("test Message")
        .setContentText(message)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);

Then, in your activity class (here it is MainActivity), you can retrieve the bundle:

Bundle omData = intent.getBundleExtra("OmniataGCM");
if (omData != null) {
    Omniata.trackPushNotification(omData);
}

This article was last updated on April 21, 2017 12:47. If you didn't find your answer here, search for another article or contact our support to get in touch.