Reference
Flagship
The Flagship
class represents the SDK. It facilitates the initialization process and creation of new visitors.
start
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
application
Application
your Android application base class.
envId
String
Environment id provided by Flagship.
apiKey
String
Api authentication key provided by Flagship.
Example
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Flagship.start(getApplication(),"_ENV_ID_", "_API_KEY_", FlagshipConfig.DecisionApi()
}
}
newVisitor
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
visitorId
String
Unique visitor identifier.
consent
Boolean
Specify 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.
instanceType
Visitor.Instance
How 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
getConfig
Return the current used configuration.
Signature
fun getConfig(): FlagshipConfig<*>
Example
val currentConfiguration = Flagship.getConfig()
getVisitor
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
getStatus
Return the current SDK status. See Flagship.Status for more information.
Signature
fun getStatus(): Status
Example
val flagshipStatus = Flagship.getStatus()
stop
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
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.
BUCKETING
When 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
NOT_INITIALIZED
Flagship SDK has not been started or initialized successfully.
INITIALIZING
Flagship SDK is initializing.
PANIC
Flagship SDK is ready but is running in Panic mode: All visitor's features are disabled except 'fetchFlags' which refreshes this status.
INITIALIZED
Flagship 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. See Decision Mode section.
withLogManager
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
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.
}
})
)
withLogLevel
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
level
LogManager.Level
level of log priority.
Example
Flagship.start(
getApplication(),
"_ENV_ID_",
"_API_KEY_"
FlagshipConfig.DecisionApi()
.withLogLevel(LogManager.Level.ERROR)
)
withTimeout
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
timeout
Int
Timeout 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)
)
withFlagshipStatusListener
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
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)
}
)
withOnVisitorExposed
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
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
}
)
withCacheManager
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
customCacheManager
CacheManager?
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.
}
})
)
withTrackingManagerConfig
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
trackingManagerConfig
TrackingManagerConfig
Custom 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
))
)
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
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
hasConsented
Boolean
Set to true when the visitor has consented for personal data usage, false otherwise.
Example
visitor.setConsent(false)
hasConsented
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
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.
Signature
fun <T> updateContext(key: String, value: T)
Parameters
key
String
Context key to update.
value
T
New 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
context
HashMap
Initial 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
flagshipContext
FlagshipContext
Flagship predefined context key.
value
T
New value for the given predefined context key. Must be Number, Boolean or String type.
Example
visitor.updateContext(FlagshipContext.CARRIER_NAME, "free")
clearContext
clearContext
Clear all the visitor context values used for targeting.
Signature
fun clearContext()
Example
visitor.clearContext()
fetchFlags
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
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
key
String
Key associated with the desired flag.
Example
val displayNewFeatureFlag = visitor.getFlag("isNewFeatureEnabled")
getFlags
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
sendHit
This function will send a Hit to Flagship collect to feed campaign reporting.
Signature
fun <T> sendHit(hit: Hit<T>)
Parameters
hit
Hit
Hit to sent to the Flagship collect.
Example
visitor.sendHit(Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket"))
authenticate
authenticate
Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is logged.
Signature
fun authenticate(visitorId: String)
Parameters
visitorId
String
Unique id of the current authenticated visitor.
Example
visitor.authenticate("logged_visitor_id")
unAuthenticate
unAuthenticate
Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is disconnected.
Signature
fun unauthenticate()
Example
visitor.unAuthenticate()
collectEmotionsAIEvents
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.
Signature
fun collectEmotionsAIEvents(activity: Activity? = null): Deferred<Boolean>
Parameters
activity
Activity
The 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.
Specify if the visitor is authenticated or anonymous for experience continuity.
Signature
fun isAuthenticated(isAuthenticated: Boolean): Builder
Parameters
isAuthenticated
Boolean
boolean, true for an authenticated visitor, false for an anonymous visitor.
Example
val visitor = Flagship.newVisitor("visitor_uuid", true)
.isAuthenticated(true)
.build()
context
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
context
HashMap
Initial 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
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
onFlagStatusChanged
OnFlagStatusChanged
Implementation 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
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
SINGLE_INSTANCE
The 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_INSTANCE
The 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
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
defaultValue
T?
Fallback value for this Flag when it does not exist in Flagship, or when type mismatch with the existing one.
visitorExposed
Boolean
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. 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
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
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
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
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
keys
Return all the Flag keys contained in the collection.
Signature
fun keys(): MutableSet<String>
Example
visitor.getFlags().keys()
get
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")
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
filter
Return a new FlagCollection matching the given predicate.
Signature
fun filter(predicate: (Map.Entry<String, Flag>) -> Boolean): FlagCollection
Parameters
predicate
(Map.Entry<String, Flag>) -> Boolean
Predicate to filter the collection.
Example
val appCampaignFlags = visitor.getFlags().filter { (k, f) -> flag.metadata().campaignName == "app" }
metadata
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
toJSON
Return the collection Flags metadata as JSONObject.
Signature
fun toJSON(): JSONObject
Example
val flagCollection = visitor.getFlags()
val jsonFlagCollection = flagCollection.toJSON()
iterator
iterator
Return a FlagCollection iterator.
Signature
operator fun iterator(): Iterator<Pair<String, Flag>>
Example
val flagCollection = visitor.getFlags()
for ((k, v) in flagCollection) {
//
}
size
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
campaignId
String
Flag use-case id.
campaignName
String
Flag use-case name defined in the platform from which the Flag comes.
campaignType
String
Flag use-case type selected in the platform from which the Flag comes.
variationGroupId
String
Id of the variation group from which the Flag comes.
variationGroupName
String
Name of the Flag variation group from which the Flag comes.
variationId
Id of the variation from which the Flag comes.
variationName
Name of the variation defined on the platform from which the Flag comes.
slug
Flag use-case custom slug defined in the platform.
isReference
Is the Flag from the reference variation.
allocation
Variation allocation.
exists
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
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
withIp
Set the current user public ip.
Signature
fun withIp(ip: String): T
Parameters
ip
String
Current visitor's public IP.
Example
visitor.sendHit(
Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
.withId("8.8.8.8")
)
withResolution
withResolution
Set the current device screen resolution.
Signature
fun withResolution(width: Int, height: Int): T
Parameters
width
Int
Current visitor's device screen width.
height
Int
Current visitor's device screen height.
Example
visitor.sendHit(
Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
.withResolution(1920, 1080)
)
withSessionNumber
withSessionNumber
Set the current visitor session number.
Signature
fun withSessionNumber(number: Int): T
Parameters
number
Int
Current visitor session number.
Example
visitor.sendHit(
Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
.withSessionNumber(3)
)
withLocale
withLocale
Set the current user device locale.
Signature
fun withLocale(locale: String): T
Parameters
locale
String
Current 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
location
String
Page 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
location
String
Interface 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
category
EventCategory
Category of the event.
action
String
Event action matching your campaign goal.
Example
import com.abtasty.flagship.hits.Event
visitor.sendHit(
Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
)
withEventLabel
withEventLabel
Set a label for this event.
Signature
fun withEventLabel(label: String): Event
Parameters
label
String
Label 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
withEventValue
Set a value for this event. Must be non-negative Int.
Signature
fun withEventValue(value: Int): Event
Parameters
value
Int
Value 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
transactionId
String
Transaction unique identifier.
affiliation
String
Affiliation name matching your campaign goal.
withTotalRevenue
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
revenue
Float
Total revenue.
Example
import com.abtasty.flagship.hits.Transaction
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withTotalRevenue(99.9f)
)
withShippingCosts
withShippingCosts
Set the total shipping cost of the transaction.
Signature
fun withShippingCosts(shipping: Float): Transaction
Parameters
shipping
Float
Total of the shipping costs.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withShippingCosts(4.99f)
)
withShippingMethod
withShippingMethod
Set the shipping method.
Signature
fun withShippingMethod(shippingMethod: String): Transaction
Parameters
shippingMethod
Float
Shipping method used for the transaction.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withShippingMethod("Chrono 48")
)
withTaxes
withTaxes
Set the total taxes of the transaction.
Signature
fun withTaxes(taxes: Float): Transaction
Parameters
taxes
Float
Total taxes.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withTaxes(9.99f)
)
withCurrency
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
currency
String
Currency used for the transaction.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withCurrency("EUR")
)
withPaymentMethod
withPaymentMethod
Set the payment method for the transaction.
Signature
fun withPaymentMethod(paymentMethod: String): Transaction
Parameters
paymentMethod
String
Payment method used for the transaction.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withPaymentMethod("credit_card")
)
withItemCount
withItemCount
Set the number of items for the transaction.
Signature
fun withItemCount(itemCount: Int): Transaction
Parameters
itemCount
Int
Number of purchased items.
Example
visitor.sendHit(
Transaction("942B42042CC", "affiliation")
.withItemCount(2)
)
withCouponCode
withCouponCode
Set the coupon code used by the customer for the transaction.
Signature
fun withCouponCode(coupon: String): Transaction
Parameters
coupon
String
Coupon 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
transactionId
String
Id of the transaction linked to this item.
productName
String
Name of the product.
productSku
String
Item code or SKU.
Example
import com.abtasty.flagship.hits.Item
visitor.sendHit(
Item("942B42042CC", "Item", "U20398")
)
withItemPrice
withItemPrice
Set the item price.
Signature
fun withItemPrice(price: Float): Item
Parameters
price
Float
Item price.
Example
visitor.sendHit(
Item("942B42042CC", "Item", "U20398")
.withItemPrice(39.99f)
)
withItemQuantity
withItemQuantity
Set the number of item purchased.
Signature
fun withItemCategory(category: String): Item
Parameters
quantity
Int
Number of purchased item.
Example
visitor.sendHit(
Item("942B42042CC", "Item", "U20398")
.withItemQuantity(2)
)
withItemCategory
withItemCategory
Set the item category.
Signature
fun withItemCategory(category: String): Item
Parameters
category
String
Category 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
visitorCacheLookupTimeout
Long
Reading timeout for cached visitor data in milliseconds.
hitsCacheLookupTimeout
Long
Reading 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
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
visitorId
String
Unique visitor identifier whom information need to be cached.
data
JSONObject
Visitor information to store in your database.
lookupVisitor
lookupVisitor
This method is called when the SDK need to load visitor information from the database.
Signature
fun lookupVisitor(visitorId: String) : JSONObject
Parameters
visitorId
String
Unique visitor identifier whom information need to be loaded from the database.
flushVisitor
flushVisitor
This method is called when visitor information should be cleared from the database.
Signature
fun flushVisitor(visitorId: String)
Parameters
visitorId
String
Unique 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
cacheHits
This method is called when the SDK need to save hits into the database.
Signature
fun cacheHits(hits: HashMap<String, JSONObject>)
Parameters
hits
HashMap<String, JSONObject>
hits to store in your database.
lookupHits
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
flushHits
This method is called when hits need to be removed from the database.
Signature
fun flushHits(hitIds: ArrayList<String>)
Parameters
hitIds
ArrayList<String>
List of hit ids that need to be removed.
flushAllHits
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
cachingStrategy
CacheStrategy
Define the strategy to use for hits caching. It relies on the CacheManager provided in FlagshipConfig. Default value is CacheStrategy.CONTINUOUS_CACHING.
closingStrategy
ClosingStrategy
Define the strategy to use for remaining hits in the pool when stopping Flagship. Default value is ClosingStrategy.CACHE_PENDING_HITS.
batchTimeInterval
Long
Define a time delay between each batched hit requests in milliseconds. Default value is 10000.
maxPoolSize
Int
Define 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
CONTINUOUS_CACHING
Hits 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_CACHING
Hits 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
CACHE_PENDING_HITS
Remaining Hits in the pool will be cached into the CacheManager provided database.
BATCH_PENDING_HITS
Remaining 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.
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.
FIRST_TIME_INIT
First init of the app
sdk_firstTimeInit
Boolean
Yes
TRUE (FALSE if the init isn't the first one)
LOCALE
Language of the device
sdk_deviceLanguage
String
Yes
fr_FR
DEVICE_TYPE
Tablette / Mobile
sdk_deviceType
String
Yes
mobile
DEVICE_MODEL
Model of the device
sdk_deviceModel
String
Yes
samsung E1200
LOCATION_CITY
City geolocation
sdk_city
String
No
toulouse
LOCATION_REGION
Region geolocation
sdk_region
String
No
occitanie
LOCATION_COUNTRY
Country geolocation
sdk_country
String
No
France
LOCATION_LAT
Current Latitude
sdk_lat
Double
No
43.623647
LOCATION_LONG
Current Longitude
sdk_long
Double
No
1.445397
OS_NAME
Name of the OS
sdk_osName
String
Yes
android / iOS
OS_VERSION
Version of the OS
sdk_osVersion
String
Yes
pie
API_LEVEL
Version of the API
sdk_apiLevel
Integer
Yes
24
ANDROID_VERSION / IOS VERSION
Version of Android
sdk_androidVersion / sdk_iOSVersion
String
Yes
9
MVNO / carrierName
Name of the carrier or mobile virtual network operator
sdk_carrierName
String
Yes
orange
DEV_MODE
Is the app in debug mode?
sdk_devMode
Boolean
Yes
TRUE
VISITOR_ID
Visitor_id of the user
sdk_visitorId
String
Yes
toto2000
INTERNET_CONNECTION
What is the internet connection
sdk_internetConnection
String
No
3g
APP_VERSION_NAME
Version name of the app
sdk_versionName
String
No
1.1.2-beta
APP_VERSION_CODE
Version code of the app
sdk_versionCode
Integer
No
40
FLAGSHIP_VERSION
Version of the Flagship SDK
sdk_fsVersion
String
Yes
1.1.2
INTERFACE_NAME
Name of the interface
sdk_interfaceName
String
No
ProductPage
FlagStatus
Enum class that represents a Flag Status.
Values
NOT_FOUND
Flag does not exist in Flagship SDK.
FETCH_REQUIRED
Flags are out of date, it is necessary to call fetchFlags() function to update them.
FETCHING
Flags are currently being fetched.
PANIC
SDK is in Panic mode, all Flags will fallback with default values, exposition will be disabled.
FETCHED
Flags 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
onFlagStatusChanged
This function will be called each time the FlagStatus has changed.
Signature
fun onFlagStatusChanged(newStatus: FlagStatus)
Parameters
newStatus
FlagStatus
New Flag Status
onFlagStatusFetchRequired
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
reason
FetchFlagsRequiredStatusReason
Fetch required reason
onFlagStatusFetched
onFlagStatusFetched
This function will be called each time Flags have been fetched and updated successfully.
Signature
fun onFlagStatusChanged(newStatus: FlagStatus)
Parameters
reason
FetchFlagsRequiredStatusReason
Fetch required reason
Last updated
Was this helpful?