Android Kotlin SDK

Version: 1.0.1

SDK Support & Compatibility

  • zeta-core : android 7(API-24) and above
  • zeta-push: android 7(API-24) and above


Install SDK

  • zeta-core
implementation(“com.zeta.android.core:1.0.0”)

  • zeta-push
implementation(“com.zeta.android.push:1.0.0”)


Initialize SDK

//ZetaClient should initialize inside the application class onCreate
//Create the configuration object
val config = ZTConfig(
            clientSiteId = siteId,
            clientSecret = clientSecret,
            isLoggingEnabled = true,
            optIn = true,
            region = ZTRegion.US
        )
//Initialize method
ZetaClient.initialize(this, config)
ZTPush.initConfig(
            ZTNotificationConfig(
                smallIcon = applicationInfo.icon,
                color = Color.GREEN,
                notificationChannel = ZTNotificationChannel(
                    id = "ApplicationTestChanne",
                    name = "Application Test Channe",
                    description = "Test Channel Description",
                )
            )
        )

ZTConfig parameters

  • clientSiteId: will be provided from ZMP console post successful app registration
  • isLoggingEnabled: The value for enabling SDK logs, by default the parameter value will be disabled
  • clientSecret: will be provided from ZMP console post successful app registration
  • optIn: The value of enabling the SDK to track events and send data to the backend.
  • region: The SDK supports region configuration; the correct region should be referenced from ZTRegion class. Region cannot be interchanged for same ZMP Account.

ZTNotificationConfig parameters

  • smallIcon: Set the small icon to use in the notification layouts.
  • largeIcon : Sets the large icon that is shown in the notification(This will be removed in version 1.0.0)
  • color: Accent color to be applied to the notification.
  • enableAppLaunch: Enable SDK launch the application, when notification actions are missing in payload(By default this flag will be true)
  • notificationChannel: Notification channel info. If this configuration is not provided, the SDK will create a DEFAULT channel

ZTNotificationChannel parameters

  • id: Channel id
  • name: Channel Name
  • description: Channel description
  • showBadge: Enable/Disable badge icon for the channel(By default this flag will be true).
  • autoCancel: Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel(By default this flag will be true)
  • notificationSound: Resource id for the explicit sound file(Optional field)

How to initialize the ZetaClient?

The ZetaClient should be initialized inside the onCreate method of your application. During this initialization, only the site ID is a mandatory field, and by default, logging will be disabled.

For the SDK to communicate with the server, clientSecret is required. The clientSecret can be provided either during the SDK initialization or through a late setClientSecret method.

ZetaClient.setClientSecret(context = applicationContext, clientSecret = clientSecretKey)

How get the BSIN from the SDK?
The SDK exposes a method for retrieving BSIN changes. This callback lambda will be triggered whenever a BSIN change occurs from the SDK side.

ZetaClient.setOnBsinChange { bsin ->}

Tracking Opt-in and Opt-out

When the application does not require the SDK to track events and user properties, it can utilize the opt-out feature. The application sends the opt-out configuration as part of its initialization or can call a separate opt-out method. If the application is using SDK-exposed methods for opting in or out, the same status should be sent through the SDK initialization configuration during the next launch. Otherwise, the configuration value may overwrite the opt-in/out status. Once the SDK receives the opt-out request, it will immediately stop all communication with the back end, and any data cached in the database will also be cleared. Until the application opts back in, the SDK will neither collect data from the application nor send data to the server. The application can opt in or out at any time during its lifecycle. After opting out, if the application opts back in, the SDK will consider it a fresh launch.

Tracking opt-out

Tracking of SDK can be disabled in two ways:

Pass opt-in as false during initialization

ZTConfig(  
    clientSiteId = siteId,  
    isLoggingEnabled = true,  
    optIn = optInStatus, //This value can be true or false  
    region = ZTRegion.EU  
)

Call stop tracking method

ZetaClient.optOutFromTracking(context = context)

Here context is the Application context.

Tracking opt-in

ZetaClient.optInForTracking(uid = userId)

uid: At the time of opt-in, the uid field is optional for identifying the user from the SDK's perspective. If the application does not provide a user ID, the SDK will consider the user as an anonymous user.

User Identification

The ZTUserManager instance is exposed from the ZetaClient for performing user operations. The client app can update the user data using the builder pattern or by creating a ZTUser object at the app level and calling the setUser method to pass the data to the SDK.

    ZetaClient.user.builder()
            .setName(name = name.value)
            .setFirstName(firstName.value)
            .setLastName(lastName.value)
            .setSource(source.value)
            .setEmail(ZTUserEmail(email = email.value, additionalInfo = emailAdditionalInfo.value))
            .setUid(userid.value).setSignedUpAt(signedUp.value).setPhone(
                ZTUserPhone(
                    phone = phoneContact.value, additionalInfo = phoneAdditionalInfo.value
                )
            ).submit()
    
    or
    val user= ZTUser(name = "John Wick")
    ZetaClient.user.setUser(user)

For contact information (email, phone number, device token), the client app can also pass the additional info to the SDK.

val contactAdditionalInfo = ZTContactAdditionalInfo(
    preferences = preferencesList,
    subscriptionStatus = subscriptionStatus.value,
    inactivityReason = contactInactivityReason.value,
    signedUpAt = contactSignedUpAt.value,
    doubleOptInStatus = contactDoubleOptInStatus.value,
    phoneType = contactPhoneType.value,
    lastClicked = contactLastClicked.value,
    lastSent = contactLastSent.value,
    lastOpened = contactLastOpened.value,
    contactProperties = contactExtraPropertyMap.toMap()
)

preferences: List<String>,  the defaule value will be "standard"
subscriptionStatus:ZTContactSubscriptionStatus, This field value can be, NEW, ACTIVE,INACTIVE
contactProperties: Additioncal contact properties can through this map
  • preference of contact defaults to standard but other preferences can be added/customized within the settings menu in ZMP. Only those defined values can be passed in preference

Date Time Format Specification

All date and time values should be in ISO 8601 format. The SDK exposes an extension method for converting millisecond timestamps to ISO 8601 format. The method usage example.

System.currentTimeMillis().formatDateToIso()

How to Start the User Session?

The SDK supports tracking user session-specific properties and events. Setting the uid property will facilitate session tracking.

  • Using builder pattern
ZetaClient.user.builder().setUid(userName.value).submit()
  • Using the User Object
val user = ZTUser(uid = "userId")
ZetaClient.user.setUser(user)

How to Clear the User Session?

The user manager's clear method will remove the stored user session

ZetaClient.user.clear()

How to pass appid, gaid(advertisementId) and firebase device token?

  • App Set Id : To set the app ID, use the following method:
ZetaClient.user.setAppSetId(id)
  • Google AdvertisementId(GAID) : To set the Google Advertisement ID, use the following method:
ZetaClient.user.setAdvertisementId(id!!)
  • Firebase device token : To set the Firebase device token, use the following method:
ZetaClient.user.updatePushToken(token)

Firebase Registration

The application needs to handle Firebase registration and must keep the google-services.jsonfile inside the project/app folder.



Event Tracking

Auto tracked events

  • first_open: This event is generated only once when the app is launched for the first time.
  • app_active: This event is generated whenever the app transitions from the background to the foreground.
  • app_inactive: This event is generated whenever the app transitions from the foreground to the background.

Defined events

Screen Name Tracking

screen_name: This event is used for tracking user screen navigation. The provided screen name will be cached, and for subsequent events, the screen_name will be added as a property.

ZetaClient.event.trackScreenName(screenName = screenName)

Location Tracking

location: This event can be called by passing the location coordinates along foreground/background state. The foreground/background state indicates whether the location data is collected when the app is in the foreground or background.The provided location will be cached, and for subsequent events, the location details will be added as a property.

   ZetaClient.event.trackLocation(
    latitude = latitude,
    longitude = longitude,
    isForeground = true
)

Custom Events

The SDK accepts custom events. To send custom events, the application needs to pass the event name and properties to the SDK.

  • eventName: A meaningful name that describes the event.
  • properties: A map of event properties, where the property values should be JSON encodable and decodable. If any property value is not JSON encodable, the entire event will be discarded.
ZetaClient.event.send(eventName = eventName.value, properties = eventMap)


Push Notification Setup

To set up push notifications, the application needs to add the dependency for the push library. If the application includes the push library, there is no need to additionally include the core library for supporting user properties and events.

The application needs to manage Firebase registration and ensure that the google-services.json file is placed in the correct path (project/app).

The push notification service will not work without Google Play services, so the application must ensure that the device has Google Play services installed.

For Android 13 and above, user permission is required to show notifications, and the application must handle this permission appropriately.


How add the dependency?

To add the push library dependency, include the following line in your build.gradle file:

implementation("com.zeta.android:push:1.0.0")

Before using the library ensure we are using the latest version.


How to configure push service?

The SDK includes a built-in push service that needs to be registered in the application manifest file. Add the following snippet to your AndroidManifest.xml:

<service
    android:name="com.zeta.push.ZTPushService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Configure the push notification and channel info:

ZTPush.setNotificationConfig(
    ZTNotificationConfig(
        smallIcon = applicationInfo.icon,
        color = Color.GREEN,
        enableAppLaunch = true,
        notificationChannel = ZTNotificationChannel(
            id = "ApplicationTestChannel",
            name = "Application Test Channel",
            description = "Test Channel Description",
            showBadge = true,
            autoCancel = true,
            notificationSound = R.raw.test_ring_tone_1
        )
    )
)

ZTNotificationConfig parameters

  • smallIcon : Set the small icon to use in the notification layouts.
  • color : Accent color to be applied to the notification.
  • enableAppLaunch : Enable SDK launch the application when user tap on it, when notification actions are missing in payload(By default this flag will be true).
  • notificationChannel : Notification channel info. If this configuration is not provided, the SDK will create a DEFAULT channel.

ZTNotificationChannel parameters

  • id: Channel id
  • name: Channel Name
  • description: Channel description
  • showBadge: Enable/Disable badge icon for the channel(By default this flag will be true).
  • autoCancel : Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel(By default this flag will be true)
  • notificationSound : Resource id for the explicit sound file(Optional field)

Setting Up Push Notification Deep Linking

When a user taps on the notification, the intent will be delivered to the application. In the AndroidManifest.xml, the deep link URL must be registered to launch the activity. For example:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />

    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />

    <data android:scheme="com.zeta.android.demo" />
    <data android:host="home" />

</intent-filter>

Tracking Foreground Notification Deep Link Clicks

The notification payload will be delivered to the registered activity through the intent. The deep link URI value can be retrieved from intent.data. To process the activity intent, pass it to the SDK. If the intent is valid, the SDK will return a valid notification info object, which can then be used for tracking. For example:

    private fun handleIntent(intent: Intent?) {
        val data = intent?.data
        data?.let { uri ->
            appViewModel.setDeepLinkUri(uri)
        }
        intent?.let {
            val notificationInfo = ZTPush.getNotificationInfo(intent)
            notificationInfo?.let {
                ZTPush.trackEvent(notificationInfo)
                ZTPush.removeNotification(
                    context = applicationContext,
                    notificationInfo.localNotificationId
                )
            }
            intent.data = null, // Clear the data after processing
        }
    }

Setting Up Push Notification Action Callback

Foreground Action

When a user taps on a notification action button while in the foreground, the respective action will be delivered to the application. The application should register the specified action in the activity's configuration section in the AndroidManifest.xml. For example:

<intent-filter>
    <action android:name="com.zeta.demoapp.open_notification" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Tracking Foreground Action Button Clicks

The notification payload will be delivered to the registered activity through the intent. To process the activity intent, pass it to the SDK. If the intent is valid, the SDK will return a valid notification info object, which can then be used for tracking. For example:

val notificationInfo = ZTPush.getNotificationInfo(intent)
notificationInfo?.let {
    ZTPush.trackEvent(notificationInfo)
    //Removing notifcation from the system tray.
    ZTPush.removeNotification(
        context = applicationContext,
        notificationInfo.localNotificationId
    )
}

Background Action button

When a user taps on a background action button, the SDK will pass the callback to the method below. Once this method is invoked, the application can process it. For this action, the SDK will automatically create the event:

ZTPush.setActionBackgroundCallback { data ->
   //Process the noticiation background action click
}

Custom Push Service

If you want to use your own custom PushService, implement the following method to send the device token to the server in the onNewToken method:

override fun onNewToken(token: String) {
    super.onNewToken(token)
    ZetaClient.user.updatePushToken(token)
}

Processing Push Notifications

To process the push notifications, use the following method:

 ZTPush.handleMessage(
            context = applicationContext,
            remoteMessage = message
        )

If the above method returns true, the SDK is able to process the notification. If it returns false, the application needs to handle the notification accordingly.

Delivery Status of Push Notifications

The SDK automatically captures the delivery status of push notifications in both cases(in service/Custom Service)