Reference

Flagship

The Flagship class represents the SDK. It facilitates the initialization process and creation of new visitors.


start

Initialize and start the flagship SDK, using your credential with a custom configuration implementation.


Signature

suspend fun start(application: Application, envId: String, apiKey: String, config: FlagshipConfig<*>)


Parameters

ParameterTypeDescription
applicationApplicationyour Android application base class.
envIdStringEnvironment id provided by Flagship.
apiKeyStringApi authentication key provided by Flagship.
configFlagshipConfig<*>Flagship configuration to use. See Configuration.

📘

Environment ID and API Key

You can find your Environment Id and your API Key on your Flagship account, in Parameters > Environment & Security.


Example

class MyActivity : Activity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
      
        super.onCreate(savedInstanceState)
        
        Flagship.start(getApplication(),"_ENV_ID_", "_API_KEY_", FlagshipConfig.DecisionApi()
    }
}

newVisitor

Return a Visitor Builder class that wiill help to create a new visitor instance.


Signature

fun newVisitor(visitorId: String, consent: Boolean, instanceType: Visitor.Instance = Visitor.Instance.SINGLE_INSTANCE): Visitor.Builder


Parameters

ParameterTypeDescription
visitorIdStringUnique visitor identifier.
consentBooleanSpecify if the visitor has consented for personal data usage. When false some features will be deactivated, Pending hits and cache will be deactivated and cleared.
instanceTypeVisitor.InstanceHow Flagship SDK should handle the newly created visitor instance. (Default is SINGLE_INSTANCE). See Visitor.Instance for more information.

Example

 val visitor = Flagship.newVisitor("visitor_uuid", true)
                .context(hashMapOf("isVIP" to true))
                .build()

getConfig

Return the current used configuration.


Signature

fun getConfig(): FlagshipConfig<*>


Example

val currentConfiguration = Flagship.getConfig()

getVisitor

This method will return any previous created visitor instance initialized with the SINGLE_INSTANCE (Set by default) option.


Signature

fun getVisitor() : Visitor?


Example

 val visitor = Flagship.getVisitor()

getStatus

Return the current SDK status. See Flagship.Status for more information.


Signature

fun getStatus(): Status


Example

 val flagshipStatus = Flagship.getStatus()

stop

Stop the Flagship SDK. Any data and background job will be cleared or stopped.


Signature

suspend fun stop()


Example

Flagship.stop()

Flagship.DecisionMode

This enum class used by the implementation of FlagshipConfig will makes the Flagship SDK run in two different modes.


Values

DecisionModeDescription
DECISION_API(default) When the SDK is running in DECISION_API mode, the campaign assignments and targeting validation take place server-side. In this mode, each call to the fetchFlags method to refresh the flags will create an HTTP request.
BUCKETINGWhen the SDK is running in BUCKETING mode, the SDK downloads all the campaigns configurations at once in a single bucketing file so that variation assignment and targeting validation can be computed client-side by the SDK. This bucketing file is stored in cache and will only be downloaded again when campaign configurations are modified in the Flagship interface. **Learn more **

Flagship.FlagshipStatus

This enum class defines the current SDK Status. All possible status are:


Values

StatusDescription
NOT_INITIALIZEDFlagship SDK has not been started or initialized successfully.
INITIALIZINGFlagship SDK is initializing.
PANICFlagship SDK is ready but is running in Panic mode: All visitor's features are disabled except 'fetchFlags' which refreshes this status.
INITIALIZEDFlagship SDK is ready to use.

FlagshipConfig

This class aims to help you to configure the SDK via the following two available config implementations: DecisionApi and Bucketing. SeeDecision Mode section.


withLogManager

The withLogManager function of the FlagshipConfig class, set a custom implementation of LogManager in order to receive logs from the SDK.


Signature

fun withLogManager(customLogManager: LogManager): T


Parameters

ParameterTypeDescription
customLogManagerLogManagerCustom implementation of LogManager.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.DecisionApi()
      .withLogManager(object : LogManager() {
        override fun onLog(level: Level, tag: String, message: String) {
          // Intercept SDK logs.
        }
      })
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.Bucketing()
      .withLogManager(object : LogManager() {
        override fun onLog(level: Level, tag: String, message: String) {
          // Intercept SDK logs.
        }
      })
)

withLogLevel

The withLogLevel function of the FlagshipConfig class can be used to filter logs emitted by the SDK.


Signature

fun withLogLevel(level: LogManager.Level): T


Parameters

ParameterTypeDescription
levelLogManager.Levellevel of log priority.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.DecisionApi()
    	.withLogLevel(LogManager.Level.ERROR)
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.Bucketing()
    	.withLogLevel(LogManager.Level.ERROR)
)

withTimeout

The withTimeout function of the FlagshipConfig class can be used to set http request timeouts in milliseconds for api requests.


Signature

withTimeout(timeout: Int): T


Parameters

ParameterTypeDescription
timeoutIntTimeout in milliseconds for connect and read timeouts. Default value is 2000.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
     FlagshipConfig.DecisionApi()
    	.withLogLevel(LogManager.Level.ERROR)
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.Bucketing()
    	.withLogLevel(LogManager.Level.ERROR)
)

withFlagshipStatusListener

The withStatusListener function of the FlagshipConfig class can be used to define a new listener in order to get callback when the SDK status has changed.


Signature

fun withFlagshipStatusListener(listener: ((Flagship.Status) -> Unit)): T


Parameters

ParameterTypeDescription
listener((Flagship.Status) -> Unit))Lambda to invoke when SDK Status has changed.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
  	FlagshipConfig.DecisionApi()
    	.withStatusListener { newStatus ->
        println("NEW STATUS = " + newStatus)
      }
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
  	FlagshipConfig.Bucketing()
     .withStatusListener { newStatus ->
        println("NEW STATUS = " + newStatus)
      }
)

withOnVisitorExposed

The withOnVisitorExposed function of the FlagshipConfig class can be used to invoke a lambda when a visitor has been exposed to a campaign Flag. It is useful to centralize Flag exposition before sending them to third party tools.


Signature

fun withOnVisitorExposed(onVisitorExposed: ((VisitorExposed, ExposedFlag<*>) -> (Unit))): T


Parameters

ParameterTypeDescription
listener((Flagship.Status) -> Unit))Lambda to invoke when SDK Status has changed.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.DecisionApi()
      .withOnVisitorExposed { visitorExposed, exposedFlag ->
        // Send data to third party tool
      }
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
  	FlagshipConfig.Bucketing()
      .withOnVisitorExposed { visitorExposed, exposedFlag ->
        // Send data to third party tool
      }
)

withCacheManager

The withCacheManager function of the FlagshipConfig class can be used to provide a custom cache manager. Implement the IVisitorCacheImplementation interface to cache Visitor data or/and IHitCacheImplementation to cache Hits data. See CacheManager.


Signature

fun withCacheManager(customCacheManager: CacheManager?): T


Parameters

ParameterTypeDescription
customCacheManagerCacheManager?Custom implementation of cache manager.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
     FlagshipConfig.DecisionApi()
      .withCacheManager(object : CacheManager(), IVisitorCacheImplementation, IHitCacheImplementation {
          override fun cacheHits(hits: HashMap<String, JSONObject>) {
            // Cache hits in your own database.
          }

          override fun lookupHits(): HashMap<String, JSONObject> {
            // Load hits from your own database.
          }

          override fun flushHits(hitIds: ArrayList<String>) {
            // Delete hits from your own database.
          }

          override fun flushAllHits() {
            // Delete all hits in your own database.
          }

          override fun cacheVisitor(visitorId: String, data: JSONObject) {
             // Cache visitor data in your own database.
          }

          override fun lookupVisitor(visitorId: String): JSONObject {
            // Load visitor data from  your own database.
          }

          override fun flushVisitor(visitorId: String) {
              // Delete visitor data from  your own database.
          }
        })
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
     FlagshipConfig.Bucketing()
      .withCacheManager(object : CacheManager(), IVisitorCacheImplementation, IHitCacheImplementation {
          override fun cacheHits(hits: HashMap<String, JSONObject>) {
            // Cache hits in your own database.
          }

          override fun lookupHits(): HashMap<String, JSONObject> {
            // Load hits from your own database.
          }

          override fun flushHits(hitIds: ArrayList<String>) {
            // Delete hits from your own database.
          }

          override fun flushAllHits() {
            // Delete all hits in your own database.
          }

          override fun cacheVisitor(visitorId: String, data: JSONObject) {
             // Cache visitor data in your own database.
          }

          override fun lookupVisitor(visitorId: String): JSONObject {
            // Load visitor data from  your own database.
          }

          override fun flushVisitor(visitorId: String) {
              // Delete visitor data from  your own database.
          }
        })
)

withTrackingManagerConfig

The withTrackingManagerConfig function of the FlagshipConfig class can be used to Specify a custom tracking manager configuration. See TrackingManagerConfig.


Signature

fun withTrackingManagerConfig(trackingManagerConfig: TrackingManagerConfig): T


Parameters

ParameterTypeDescription
trackingManagerConfigTrackingManagerConfigCustom implementation of cache manager.

Example

Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.DecisionApi()
    .withTrackingManagerConfig(TrackingManagerConfig(
      cachingStrategy = CacheStrategy.PERIODIC_CACHING,
      closingStrategy = ClosingStrategy.CACHE_PENDING_HITS,
      batchTimeInterval = 20000,
      maxPoolSize = 20
    ))
)
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
  	"_API_KEY_"
    FlagshipConfig.Bucketing()
    .withTrackingManagerConfig(TrackingManagerConfig(
      cachingStrategy = CacheStrategy.PERIODIC_CACHING,
      closingStrategy = ClosingStrategy.CACHE_PENDING_HITS,
      batchTimeInterval = 20000,
      maxPoolSize = 20
    ))
)

Visitor

The Visitor class represents a unique user within your application. It is useful to manage visitor's data and fetching the corresponding flags from the Flagship platform .

A new visitor instance can be created using the newVisitor method from the Flagship class which returns a Visitor Builder class.


setConsent

Specify if the visitor has consented for personal data usage. When false some features will be deactivated, cache will be deactivated and cleared.


Signature

fun setConsent(hasConsented: Boolean)


Parameters

ParameterTypeDescription
hasConsentedBooleanSet to true when the visitor has consented for personal data usage, false otherwise.

Example

visitor.setConsent(false)

hasConsented

Return true if the visitor has given his consent for private data usage, false otherwise.


Signature

fun hasConsented(): Boolean


Example

val hasConsented = visitor.hasConsented()

updateContext

Update the visitor context values, matching the given keys, used for targeting. A new context value associated with this key will be created if there is no previous matching value. Context keys must be String, and values types must be one of the following : Number, Boolean, String.


📘

Refresh Flags

When Visitor's context is changed, it may target different campaigns so assigned flags should be refreshed by calling the fetchFlags() function afterward.


Signature

fun <T> updateContext(key: String, value: T)


Parameters

ParameterTypeDescription
keyStringContext key to update.
valueTNew value for the given context key. Must be Number, Boolean or String type.

Example

visitor.updateContext("returning_visitor", true)

Signature

fun updateContext(context: HashMap<String, Any>)



Parameters

ParameterTypeDescription
contextHashMapInitial context HashMap. keys must be String, and values types must be one of the following : Number, Boolean, String.

Example

visitor.updateContext(hashMapOf("returning_visitor" to true, "visitor_landing_page" to "https://www.mydomain.com"))

Signature

fun <T> updateContext(flagshipContext: FlagshipContext<T>, value: T)


Parameters

ParameterTypeDescription
flagshipContextFlagshipContextFlagship predefined context key.
valueTNew value for the given predefined context key. Must be Number, Boolean or String type.

Example

   visitor.updateContext(FlagshipContext.CARRIER_NAME, "free")

clearContext

Clear all the visitor context values used for targeting.


📘

Refresh Flags

When Visitor's context is changed, it may target different campaigns so assigned flags should be refreshed by calling the fetchFlags() function afterward.


Signature

fun clearContext()


Example

visitor.clearContext()


fetchFlags

This function will fetch campaigns flags from campaigns that target visitor's context.


Signature

fun fetchFlags(): Deferred<IVisitor>


Example

runBlocking {
	visitor.fetchFlags().await()
}

getFlag

This function will return a flag object containing the current value returned by Flagship and the associated campaign information. If the key is not found an empty Flag object with the default value will be returned. See Flag for more information.


Signature

fun getFlag(key: String)


Parameters

ParameterTypeDescription
keyStringKey associated with the desired flag.

Example

val displayNewFeatureFlag = visitor.getFlag("isNewFeatureEnabled")

getFlags

This function will return a FlagCollection containing the all the current flags returned by Flagship and the associated campaign information. See FlagCollection for more information.


Signature

fun getFlags(): FlagCollection


Example

val allFlags = visitor.getFlags()

sendHit

This function will send a Hit to Flagship collect to feed campaign reporting.


Signature

fun <T> sendHit(hit: Hit<T>)


Parameters

ParameterTypeDescription
hitHitHit to sent to the Flagship collect.

Example

visitor.sendHit(Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket"))

authenticate

Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is logged.


📘

Refresh Flags

When authentication status is changed, it may target different campaigns so assigned flags should be refreshed by calling the fetchFlags() function afterward.



Signature

fun authenticate(visitorId: String)


Parameters

ParameterTypeDescription
visitorIdStringUnique id of the current authenticated visitor.

Example

visitor.authenticate("logged_visitor_id")

unAuthenticate

Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is disconnected.


📘

Refresh Flags

When authentication status is changed, it may target different campaigns so assigned flags should be refreshed by calling the fetchFlags() function afterward.


Signature

fun unauthenticate()


Example

visitor.unAuthenticate()

collectEmotionsAIEvents

Start collecting events for the EmotionAI Feature if it is enabled on platform side. Returns a Job with a boolean result meaning EmotionsAI collect has ended successfully or not. This feature requires a feature activation plan on the platform side, contact us to know more about. When full plan is enabled the EmotionsAI scoring will be automatically added to your visitor context and in local cache.


📘

Notes

This method needs the SDK to be initialized successfully and to have the visitor's consent, and that there is no previous score already present in the cache to run.


Signature

fun collectEmotionsAIEvents(activity: Activity? = null): Deferred<Boolean>


Parameters

ParameterTypeDescription
activityActivityThe SDK will listen activities changes by setting a WindowCallback but it is possible to pass the current activity reference where Emotion AI events need to be collected first.

Example

visitor.collectEmotionsAIEvents(this@MainActivity)


Visitor.Builder

This class is an helper for Visitor instance creation.


isAuthenticated

Specify if the visitor is authenticated or anonymous for experience continuity.


Signature

fun isAuthenticated(isAuthenticated: Boolean): Builder


Parameters

ParameterTypeDescription
isAuthenticatedBooleanboolean, true for an authenticated visitor, false for an anonymous visitor.

Example

val visitor = Flagship.newVisitor("visitor_uuid", true)
  .isAuthenticated(true)
  .build()

context

Specify visitor initial context key / values used for tar campaign targeting. Context keys must be String, and values types must be one of the following : Number, Boolean, String.


Signature

fun context(context: HashMap<String, Any>): Builder


Parameters

ParameterTypeDescription
contextHashMapInitial context HashMap. keys must be String, and values types must be one of the following : Number, Boolean, String.

Example

 val visitor = Flagship.newVisitor("visitor_uuid", true)
  	.context(hashMapOf("isVIP" to true))
  	.build()

onFlagStatusChanged

Set a FlagStatusChanged callback to be notified when Flags are out of date and need to be fetched or when flags have been successfully fetched. More info on OnFlagStatusChanged.


Signature

fun onFlagStatusChanged(onFlagStatusChanged: OnFlagStatusChanged): Builder


Parameters

ParameterTypeDescription
onFlagStatusChangedOnFlagStatusChangedImplementation of OnFlagStatusChanged interface.

Example

 val visitor = Flagship.newVisitor("visitor_abcd", true)
  .onFlagStatusChanged(object : OnFlagStatusChanged {
    override fun onFlagStatusChanged(newStatus: FlagStatus) {
      //todo
    }

    override fun onFlagStatusFetchRequired(reason: FetchFlagsRequiredStatusReason) {
      //todo
    }

    override fun onFlagStatusFetched() {
      //todo
    }
  })
  .build()

build

Build the visitor instance.


Signature

fun build(): Visitor


Example

 val visitor = Flagship.newVisitor("visitor_uuid", true)
  	.isAuthenticated(true)
  	.context(hashMapOf("isVIP" to true))
  	.build()

Visitor.Instance

This enum class allows to define how Flagship SDK should handle the newly create visitor instance.


Values

StatusDescription
SINGLE_INSTANCEThe newly created visitor instance will be returned and saved into the Flagship singleton. Call Flagship.getVisitor() to retrieve the instance. This option should be adopted on applications that handle only one visitor at the same time. This is the default value when a visitor is created.
NEW_INSTANCEThe newly created visitor instance wont be saved and will simply be returned. Any previous visitor instance will have to be recreated. This option should be adopted on applications that handle multiple visitors at the same time.

Flag

This class represents a flag in the Flagship SDK. It helps you retrieve the flag value, access its metadata, expose the flag, verify the flag's existence, and get the flag status with the following API.

A Flag instance will be returned when the function [getFlag](doc:android-reference#getflag) from the Visitor class is called.


value

Return and consume the current value for this flag or return default value when the flag doesn't exist or when the current flag value type and default value type mismatch. Consuming the value will allow flag activation.


Signature

inline fun <reified T: Any?> value(defaultValue: T?, visitorExposed: Boolean = true): T?


Parameters

ParameterTypeDescription
defaultValueT?Fallback value for this Flag when it does not exist in Flagship, or when type mismatch with the existing one.
visitorExposedBooleanTells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. Default value is true. If needed, it is possible to set this param to false and call userExposed() afterward when the user sees it.

Example

val isNewFeatureEnabledFlag = visitor.getFlag("isNewFeatureEnabled", false)
val displayNewFeature = isNewFeatureEnabledFlag.value()

when (displayNewFeature) {
  true -> {
    //Display the feature
  }
  else -> {
    //Hide the feature
  }
}

metadata

Return the campaign information metadata or an Empty flag metadata object if the flag doesn't exist.


Signature

fun metadata(): FlagMetadata


Example

val isNewFeatureEnabledMetadata = visitor.getFlag("isNewFeatureEnabled", false)
  .metadata()

visitorExposed

Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. Only Flags whose value was consumed with value() beforehand will be exposed.


Signature

fun visitorExposed()


Example

val homeScreenLabelFlag = visitor.getFlag("homeScreenLabel", false)
val displayNewFeature = homeScreenLabelFlag.value(false)
//display new label
homeScreenLabelFlag.visitorExposed())

exists

Check and return true if the current flag exists in Flagship SDK, false otherwise.

Signature

fun exists(): Boolean

Example

val doesFlagExist = visitor.getFlag("homeScreenLabel", false).exists()

status

Return the status for this Flag. See FlagStatus.


Signature

fun status(): FlagStatus


Example

val myFlagStatus visitor.getFlag("myFlag", "default").status()

Flag collection

This class holds a collection of Flag and helpers to manipulate them.


keys

Return all the Flag keys contained in the collection.


Signature

fun keys(): MutableSet<String>


Example

visitor.getFlags().keys()

get

Return a Flag from the collection.


Signature

operator fun get(key: String): Flag


Example

val flagCollection = visitor.getFlags()
val flag = flagCollection["my_flag"]
val flag2 = flagCollection.get("my_flag_2")

exposeAll

Expose all the flags in the collection. Only the ones whose value has been consumed will be exposed.


Signature

fun exposeAll()


Example

visitor.getFlags().exposeAll()

filter

Return a new FlagCollection matching the given predicate.


Signature

fun filter(predicate: (Map.Entry<String, Flag>) -> Boolean): FlagCollection


Parameters

ParameterTypeDescription
predicate(Map.Entry<String, Flag>) -> BooleanPredicate to filter the collection.

Example

val appCampaignFlags = visitor.getFlags().filter { (k, f) -> flag.metadata().campaignName == "app" }

metadata

Return a map of Flag FlagMetadata from the collection.


Signature

fun metadata(): Map<String, FlagMetadata>


Example

val flagCollection = visitor.getFlags()
val flagCollectionMetadata = flagCollection.metadata()

toJSON

Return the collection Flags metadata as JSONObject.


Signature

fun toJSON(): JSONObject


Example

val flagCollection = visitor.getFlags()
val jsonFlagCollection = flagCollection.toJSON()

iterator

Return a FlagCollection iterator.


Signature

operator fun iterator(): Iterator<Pair<String, Flag>>


Example

val flagCollection = visitor.getFlags()
for ((k, v) in flagCollection) {
  //
}

size

Return the collection size.


Signature

fun size(): Int


Example

val flagCollectionSize = visitor.getFlags().size()

FlagMetadata

This class holds all flag campaign information. FlagMetadata object can be returned by calling the [metadata](doc:android-reference#metadata)() function from a Flag instance.


Properties

PropertyTypeDescription
campaignIdStringFlag use-case id.
campaignNameStringFlag use-case name defined in the platform from which the Flag comes.
campaignTypeStringFlag use-case type selected in the platform from which the Flag comes.
variationGroupIdStringId of the variation group from which the Flag comes.
variationGroupNameStringName of the Flag variation group from which the Flag comes.
variationIdId of the variation from which the Flag comes.
variationNameName of the variation defined on the platform from which the Flag comes.
slugFlag use-case custom slug defined in the platform.
isReferenceIs the Flag from the reference variation.
allocationVariation allocation.

'exists'

Check and return true if the current flag exists and has metadatas in Flagship SDK, false otherwise.


Signature

fun exists(): Boolean


Example

val doesFlagMetadataExist = visitor.getFlag("homeScreenLabel", false).metadata().exists()

'toJSON'

Transform the current FlagMetadata instance into a json object containing all the properties.


Signature

fun toJSON(): JSONObject


Example

val flagMetadataJSON = visitor.getFlag("homeScreenLabel", false).metadata().toJSON()

Hit

This super class helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our Universal Collect documentation.

There are five different types of Hits available: Page, Screen, Event, Transaction, Item and all have common options.


withIp

Set the current user public ip.


Signature

fun withIp(ip: String): T

Parameters

ParameterTypeDescription
ipStringCurrent visitor's public IP.

Example

 visitor.sendHit(
   Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
     .withId("8.8.8.8")
 )

withResolution

Set the current device screen resolution.


Signature

fun withResolution(width: Int, height: Int): T


Parameters

ParameterTypeDescription
widthIntCurrent visitor's device screen width.
heightIntCurrent visitor's device screen height.

Example

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withResolution(1920, 1080)
)

withSessionNumber

Set the current visitor session number.


Signature

fun withSessionNumber(number: Int): T


Parameters

ParameterTypeDescription
numberIntCurrent visitor session number.

Example

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withSessionNumber(3)
)

withLocale

Set the current user device locale.


Signature

fun withLocale(locale: String): T


Parameters

ParameterTypeDescription
localeStringCurrent user device locale (must be valid iso3 code).

Example

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withLocale("fra")
)

Page

Hit to send when a user sees a web page.

Parameters

ParameterTypeDescription
locationStringPage url.

Example

import com.abtasty.flagship.hits.Page

visitor.sendHit(
  Page("www.domain.com")
)

Screen

Hit to send when a user sees an interface.


Parameters

ParameterTypeDescription
locationStringInterface name.

Example

import com.abtasty.flagship.hits.Screen

visitor.sendHit(
  Screen("PaymentActivity")
)

Event

Hit which represents an event. Can be a anything you want : for example a click or a newsletter subscription.

Parameters

ParameterTypeDescription
categoryEventCategoryCategory of the event.
actionStringEvent action matching your campaign goal.

Example

import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
)

withEventLabel

Set a label for this event.

Signature

fun withEventLabel(label: String): Event


Parameters

ParameterTypeDescription
labelStringLabel for this event.

Example

import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withEventLabel("Go to basket")
)

withEventValue

Set a value for this event. Must be non-negative Int.


Signature

fun withEventValue(value: Int): Event


Parameters

ParameterTypeDescription
valueIntValue for this event.

Example

import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withEventValue(3)
)

Transaction

Hit to send when a user complete a transaction.


Parameters

ParameterTypeDescription
transactionIdStringTransaction unique identifier.
affiliationStringAffiliation name matching your campaign goal.

withTotalRevenue

Set the total revenue associated with the transaction. This value should include any shipping or tax costs.


Signature

fun withTotalRevenue(revenue: Float): Transaction


Parameters

ParameterTypeDescription
revenueFloatTotal revenue.

Example

import com.abtasty.flagship.hits.Transaction

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withTotalRevenue(99.9f)
)

withShippingCosts

Set the total shipping cost of the transaction.


Signature

fun withShippingCosts(shipping: Float): Transaction


Parameters

ParameterTypeDescription
shippingFloatTotal of the shipping costs.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withShippingCosts(4.99f)
)

withShippingMethod

Set the shipping method.


Signature

fun withShippingMethod(shippingMethod: String): Transaction


Parameters

ParameterTypeDescription
shippingMethodFloatShipping method used for the transaction.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withShippingMethod("Chrono 48")
)

withTaxes

Set the total taxes of the transaction.


Signature

fun withTaxes(taxes: Float): Transaction


Parameters

ParameterTypeDescription
taxesFloatTotal taxes.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withTaxes(9.99f)
)

withCurrency

Set the currency used for all transaction currency values. Value should be a valid ISO 4217 currency code.


Signature

fun withCurrency(currency: String): Transaction


Parameters

ParameterTypeDescription
currencyStringCurrency used for the transaction.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withCurrency("EUR")
)

withPaymentMethod

Set the payment method for the transaction.


Signature

fun withPaymentMethod(paymentMethod: String): Transaction


Parameters

ParameterTypeDescription
paymentMethodStringPayment method used for the transaction.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withPaymentMethod("credit_card")
)

withItemCount

Set the number of items for the transaction.

Signature

fun withItemCount(itemCount: Int): Transaction

Parameters

ParameterTypeDescription
itemCountIntNumber of purchased items.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withItemCount(2)
)

withCouponCode

Set the coupon code used by the customer for the transaction.


Signature

fun withCouponCode(coupon: String): Transaction


Parameters

ParameterTypeDescription
couponStringCoupon code used for the transaction.

Example

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withCouponCode("COUPON10")
)

Item

Hit to send to associated items to a transaction. Items must be sent after the corresponding transaction.


Parameters

ParameterTypeDescription
transactionIdStringId of the transaction linked to this item.
productNameStringName of the product.
productSkuStringItem code or SKU.

Example

import com.abtasty.flagship.hits.Item

visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
)

withItemPrice

Set the item price.


Signature

fun withItemPrice(price: Float): Item


Parameters

ParameterTypeDescription
priceFloatItem price.

Example

visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemPrice(39.99f)
)

withItemQuantity

Set the number of item purchased.


Signature

fun withItemCategory(category: String): Item


Parameters

ParameterTypeDescription
quantityIntNumber of purchased item.

Example

visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemQuantity(2)
)

withItemCategory

Set the item category.


Signature

fun withItemCategory(category: String): Item


Parameters

ParameterTypeDescription
categoryStringCategory of the item.

Example

visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemCategory("Furniture")
)

CacheManager

By default the SDK implements a DefaultCacheManager which uses a local SQLiteDatabase. The CacheManager is an abstract class to implement in order to use your own caching solution. Implement IVisitorCacheImplementation and/or IHitCacheImplementation interfaces to provide a custom cache implementation for visitor's data and hits emitted by visitors.

The purpose of implementing cache is to prevent re-allocation in bucketing mode and prevent any data loss when the SDK is running offline. See more details in Managing cache.


Parameters

ParameterTypeDescription
visitorCacheLookupTimeoutLongReading timeout for cached visitor data in milliseconds.
hitsCacheLookupTimeoutLongReading timeout for cached hits in milliseconds.

IVisitorCacheImplementation

This interface specifies the methods to implement in order to cache visitors data.

Visitor cache is used for: retrieving campaign flags while offline, preventing re-allocation in bucketing mode and is used by some feature to work.


cacheVisitor

This method is called when the SDK need to upsert (insert or update) current visitor information into the database.


Signature

fun cacheVisitor(visitorId : String, data : JSONObject)


Parameters

ParameterTypeDescription
visitorIdStringUnique visitor identifier whom information need to be cached.
dataJSONObjectVisitor information to store in your database.

lookupVisitor

This method is called when the SDK need to load visitor information from the database.


Signature

fun lookupVisitor(visitorId: String) : JSONObject


Parameters

ParameterTypeDescription
visitorIdStringUnique visitor identifier whom information need to be loaded from the database.

flushVisitor

This method is called when visitor information should be cleared from the database.


Signature

fun flushVisitor(visitorId: String)


Parameters

ParameterTypeDescription
visitorIdStringUnique visitor identifier whom cached information need to be cleared from the database.

Example

Flagship.start(
  getApplication(), _ENV_ID_, _API_KEY_, FlagshipConfig.Bucketing()
    .withCacheManager(object : CacheManager(), IVisitorCacheImplementation {
      
      override fun cacheVisitor(visitorId: String, data: JSONObject) {
        // Cache visitor information in your own database.
      }

      override fun lookupVisitor(visitorId: String): JSONObject {
        // Load visitor information from your own database.
      }

      override fun flushVisitor(visitorId: String) {
        // Flush visitor information from your own database.
      }

    })
)

IHitCacheImplementation

This interface defines the methods to implement in order to cache hits for flagship SDK. Saving hits prevent any data loss while running offline.


cacheHits

This method is called when the SDK need to save hits into the database.


Signature

fun cacheHits(hits: HashMap<String, JSONObject>)


Parameters

ParameterTypeDescription
hitsHashMap<String, JSONObject>hits to store in your database.

lookupHits

This method is called when the SDK need to load hits from the database to sent them again.

Warning : Hits must be deleted from the database before being returned so your database remains clean and so hits can be inserted again if they fail to be sent a second time.


Signature

fun lookupHits(): HashMap<String, JSONObject>


flushHits

This method is called when hits need to be removed from the database.


Signature

fun flushHits(hitIds: ArrayList<String>)

Parameters

ParameterTypeDescription
hitIdsArrayList<String>List of hit ids that need to be removed.

flushAllHits

This method is called when the Flagship SDK needs to flush all the hits from cache.


Signature

fun flushAllHits()


Example

 Flagship.start(
   getApplication(), _ENV_ID_, _API_KEY_, FlagshipConfig.Bucketing()
   	.withCacheManager(object : CacheManager(), IHitCacheImplementation {
   
       	override fun cacheHits(hits: HashMap<String, JSONObject>) {
       		// Cache hits in your own database.
     		}

    		override fun lookupHits(): HashMap<String, JSONObject> {
      		// Remove and return hits from your own database
    		}

    		override fun flushHits(hitIds: ArrayList<String>) {
      		// remove hits from your own database.
    		}

    		override fun flushAllHits() {
      		// remove all hits from your own database.
    		}
		})
)

TrackingManagerConfig

This class configure the Flagship SDK Tracking Manager which gathers all visitors emitted hits in a pool and fire them in batch requests at regular time intervals withing a dedicated thread.


Parameters

ParameterTypeDescription
cachingStrategyCacheStrategyDefine the strategy to use for hits caching. It relies on the CacheManager provided in FlagshipConfig. Default value is CacheStrategy.CONTINUOUS_CACHING.
closingStrategyClosingStrategyDefine the strategy to use for remaining hits in the pool when stopping Flagship. Default value is ClosingStrategy.CACHE_PENDING_HITS.
batchTimeIntervalLongDefine a time delay between each batched hit requests in milliseconds. Default value is 10000.
maxPoolSizeIntDefine a max hit pool size that will trigger a batch request once reached. Default value is 10.

CachingStrategy

This class specifies the hits caching strategy to adopt into the TrackingManager and relies on the IHitCacheImplementation class that must be implemented in the CacheManager. Depending on the strategy the TrackingManager will request the CacheManager to CACHE, LOOK-UP or FLUSH hits from the linked database.


Value

ParameterDescription
CONTINUOUS_CACHINGHits will be continuously cached and flushed from the database. The database linked to the HitCacheImplementation class implemented in the provided CacheManager will be required each time time a hit is added or flushed from the TrackingManager pool.
PERIODIC_CACHINGHits will be cached and flushed from the database periodically.The database linked to the IHitCacheImplementation class implemented in the provided CacheManager will be required to cache/look-up/flush hits at regular time intervals. The time intervals relies on the TrackingManager 'batch intervals' option.

ClosingStrategy

This class specifies the hits closing strategy to adopt when the SDK is closing.


Value

ParameterDescription
CACHE_PENDING_HITSRemaining Hits in the pool will be cached into the CacheManager provided database.
BATCH_PENDING_HITSRemaining Hits in the pool will be sent as Batch.

Appendix

Predefined context keys


The Flagship SDK contains predefined user context keys.

The keys marked as Yes in the Auto-set by SDK column will be automatically set, while the ones marked as No need to be set by the client.

📘

Check values

Check the values sent by the SDK by enabling the logs.

You can overwrite these keys at any time. The key-value pairs will be sent to the server in the user context and can be edited in the Persona section of the Flagship platform.

SDK Variable NameDescriptionContext variable nameTypeAuto-set by SDKExample
FIRST_TIME_INITFirst init of the appsdk_firstTimeInitBooleanYesTRUE (FALSE if the init isn't the first one)
LOCALELanguage of the devicesdk_deviceLanguageStringYesfr_FR
DEVICE_TYPETablette / Mobilesdk_deviceTypeStringYesmobile
DEVICE_MODELModel of the devicesdk_deviceModelStringYessamsung E1200
LOCATION_CITYCity geolocationsdk_cityStringNotoulouse
LOCATION_REGIONRegion geolocationsdk_regionStringNooccitanie
LOCATION_COUNTRYCountry geolocationsdk_countryStringNoFrance
LOCATION_LATCurrent Latitudesdk_latDoubleNo43.623647
LOCATION_LONGCurrent Longitudesdk_longDoubleNo1.445397
OS_NAMEName of the OSsdk_osNameStringYesandroid / iOS
OS_VERSIONVersion of the OSsdk_osVersionStringYespie
API_LEVELVersion of the APIsdk_apiLevelIntegerYes24
ANDROID_VERSION / IOS VERSIONVersion of Androidsdk_androidVersion / sdk_iOSVersionStringYes9
MVNO / carrierNameName of the carrier or mobile virtual network operatorsdk_carrierNameStringYesorange
DEV_MODEIs the app in debug mode?sdk_devModeBooleanYesTRUE
VISITOR_IDVisitor_id of the usersdk_visitorIdStringYestoto2000
INTERNET_CONNECTIONWhat is the internet connectionsdk_internetConnectionStringNo3g
APP_VERSION_NAMEVersion name of the appsdk_versionNameStringNo1.1.2-beta
APP_VERSION_CODEVersion code of the appsdk_versionCodeIntegerNo40
FLAGSHIP_VERSIONVersion of the Flagship SDKsdk_fsVersionStringYes1.1.2
INTERFACE_NAMEName of the interfacesdk_interfaceNameStringNoProductPage

📘

Override values

To overwrite the keys, use the updateContext method



FlagStatus

Enum class that represents a Flag Status.


Values

StatusDescription
NOT_FOUNDFlag does not exist in Flagship SDK.
FETCH_REQUIREDFlags are out of date, it is necessary to call fetchFlags() function to update them.
FETCHINGFlags are currently being fetched.
PANICSDK is in Panic mode, all Flags will fallback with default values, exposition will be disabled.
FETCHEDFlags have been fetched and are up to date.

OnFlagStatusChanged

This interface represents a callback which could be used to be notified by the SDK when Visitor FetchStatus have changed or when Flags


onFlagStatusChanged

This function will be called each time the FlagStatus has changed.


Signature

fun onFlagStatusChanged(newStatus: FlagStatus)


Parameters

ParameterTypeDescription
newStatusFlagStatusNew Flag Status

onFlagStatusFetchRequired

This function will be called each time Flags are out of date and have to be updated by calling fetchFlags().


Signature

fun onFlagStatusChanged(newStatus: FlagStatus)


Parameters

ParameterTypeDescription
reasonFetchFlagsRequiredStatusReasonFetch required reason

onFlagStatusFetched

This function will be called each time Flags have been fetched and updated successfully.


Signature

fun onFlagStatusChanged(newStatus: FlagStatus)


Parameters

ParameterTypeDescription
reasonFetchFlagsRequiredStatusReasonFetch required reason