Skip to main content
Altcraft Docs LogoAltcraft Docs Logo
User guide iconUser guide
Developer guide iconDeveloper guide
Admin guide iconAdmin guide
English
  • Русский
  • English
Login
    User API documentationAPI interactionMatching
      Profilesarrow
    • Import profileUpdate profileImport multiple profilesUpdate multiple profilesAdd multiple profilesAdd profile to databaseImport profile to RabbitMQGet profile dataUploading profiles to a fileDelete profileSubscription fields functional updateDatabase fields functional updateMerging multiple profilesUnsubscribe profile from resourceProfile splitting
        Subscriptionsarrow
      • Add or edit subscriptionGet all profile subscriptionsGet all subscriptions from multiple profilesGet profile subscriptionDelete profile subscriptionRestore deleted subscriptionSuspend all subscriptionsUnsuspend all suspended subscriptions
        Action historyarrow
      • Get profile action historyGet multiple profiles action history
        Profile relationsarrow
      • Attach relationDetach relationModify relation propertiesOverwrite relation propertiesGet profile relations infoGet profile relations info
      Get data for multiple profiles
      Databasesarrow
    • Get database statisticsUpdate statistics on databaseGet database listGet database informationGet database fieldsDatabase wipe
      Resourcesarrow
    • Get resource statisticsUpdate statistics on resourceGet resources listGet resource informationGet resource subscription fields
      Segmentsarrow
    • Create segmentGet statistics on resourceUpdate statistics on segmentAdd or remove profileGet profile data in a static segmentUpdate segmentGet segment informationGet segments listDelete segment
      Suppression listsarrow
    • Create suppression listUpdate suppression listGet suppression list infoGet the list of suppression listsDelete suppression listUpload suppression list data to file
        Suppression list actionsarrow
      • Check if email is suppressedAdd email to suppression listAdd multiple emails to suppression listRemove email from suppression listRemove all emails from suppression listCheck if domain is suppressedAdd domain to suppression listAdd multiple domains to suppression listRemove domain from suppression listRemove all domains from suppression listCheck if phone number is suppressedAdd phone number to suppression listAdd multiple phones to suppression listRemove phone number from suppression listRemove all phone numbers from suppression list
      Templates and fragmentsarrow
    • Get templates listGet template infoDelete templateAdd templateUpdate templateChannel object
      Campaignsarrow
    • Get campaign informationGet campaign listActivate campaignComplete campaignDeactivate campaignGet campaign status
      Mailingsarrow
    • Activate mailingDeactivate mailingGet mailing listGet mailing informationGet mailing logClone mailingDelete mailingGet mailing status
        Broadcast mailingsarrow
      • Get broadcasts listGet broadcast informationCreate broadcast mailingUpdate broadcast mailingLaunch a broadcast mailing
        Regular mailingsarrow
      • Get regular mailings listGet regular mailing informationCreate regular mailingUpdate regular mailingLaunch a regular mailing
        Trigger mailingsarrow
      • Get trigger mailings listGet trigger mailing informationCreate trigger mailingUpdate trigger mailingTrigger launch (API call)Profile import + trigger mailing launchTask for bulk trigger launchTask for bulk profiles import + trigger launchBulk trigger launchBulk profiles import + trigger mailing launchClone a trigger mailingData array
      Automation scenariosarrow
    • Engage profile in scenarioImport and engage profile in scenarioBatch import and engage profiles in a scenarioTask for batch import and engaging profiles in the scenarioGet scenarios listActivate scenarioDeactivate scenario
      Loyalty Programsarrow
    • Get profile tier in a loyalty programExport points transactionsExpiring points for a periodGet profile account transactionsGet trigger promotions listAccrue points to a memberRedeem member pointsCommit temporary transactionPreliminary Order CalculationOrder ConfirmationRoll back temporary transactionCancel points transactionGet points account balanceRegister member in a loyalty programBatch adding participants to loyalty programTask for batch add participants to loyalty programRemove member from loyalty program
      Formsarrow
    • Get form informationGet form listExport form fill data by userExport form fill dataPublish formUnpublish formDelete form
      Promo codesarrow
    • Import promo codesGet promo code informationActivate promo codeUpdate promo codeAttach promo codeDetach promo codeGet all promo codes
      Goalsarrow
    • Goals and goal values registration
      Application push notificationsarrow
    • Processing and adding a subscriptionAdd app push events
      Marketarrow
      • Market objectsarrow
      • Order data objectProduct data objectSKU data objectCategories arrayCustom fields array
        Ordersarrow
      • Import order and item statusesGet orders listDelete orderGet order statusUpdate order line status
        Products and SKUarrow
      • Import products, SKUs and categoriesImport SKUs and categoriesGet products listGet SKUs listDelete productsDelete SKU
      Analytic reportsarrow
    • Get summary reportGet soft bounces reportGet undeliveries report
      Sendersarrow
    • Get senders list
        Virtual senders (Smart accounts only)arrow
      • Get virtual senders listGet virtual sender informationClone virtual senderCreate virtual senderUpdate virtual senderDelete virtual sender
      External datatables queriesarrow
      • Segmentation queriesarrow
      • Add segmentation queryUpdate segmentation queryGet segmentation query informationGet segmentation queries listDelete segmentation query
        Template queriesarrow
      • Add template queryUpdate template queryGet template query informationGet template queries listDelete template query
      Objectsarrow
    • AKMTA objectContent objectEmail rule objectFile objectProfile data objectSMS rule objectSender objectSender typesStart schedule objectSubscription objectTrigger types
      Miscellaneousarrow
    • Upload fileGet message web versionPush providersDeduplication of requestsHow to send API request with RabbitMQList of gender identificationsObtain valid values for fields: browsers, devices, tz, oses, languages
    Importing the API collection in PostmanList of API endpoints
      SDKarrow
      • mSDKarrow
        • Androidarrow
        • Quick StartSDK FunctionalitySDK ConfigurationPublic SDK API
            Provider configuration androidarrow
          • Firebase Cloud MessagingHuawei Mobile ServicesRuStore
          iOSarrow
        • Quick StartSDK FunctionalitySDK ConfigurationPublic SDK API
            Provider configurationarrow
          • Apple Push Notification ServiceFirebase Cloud MessagingHuawei Mobile Services
          React Native (Android/iOS)arrow
        • Quick StartSDK ConfigurationSDK FunctionalityPublic SDK APIProvider setup
          Flutter (Android/iOS)arrow
        • Quick StartSDK ConfigurationSDK FunctionalitySDK Public APIProvider Setup
        Managing JWT and Role Token
      Web Push SDK
  • SDK
  • mSDK
  • Android
  • SDK Functionality

SDK Functionality

tip

Before proceeding, you need to configure the SDK for your application. The detailed setup guide is available here.

Working with subscription statuses​


Changing a subscription status​

AltcraftSDK
└─ val pushSubscriptionFunctions: PublicPushSubscriptionFunctions
// Subscribe (status = SUBSCRIBED)
├─ fun pushSubscribe(
│ context: Context,
│ sync: Boolean = true,
│ profileFields: Map<String, Any?>? = null,
│ customFields: Map<String, Any?>? = null,
│ cats: List<CategoryData>? = null,
│ replace: Boolean? = null,
│ skipTriggers: Boolean? = null
│ ): Unit
// Suspend (status = SUSPENDED)
├─ fun pushSuspend(
│ context: Context,
│ sync: Boolean = true,
│ profileFields: Map<String, Any?>? = null,
│ customFields: Map<String, Any?>? = null,
│ cats: List<CategoryData>? = null,
│ replace: Boolean? = null,
│ skipTriggers: Boolean? = null
│ ): Unit
// Unsubscribe (status = UNSUBSCRIBED)
└─ fun pushUnSubscribe(
context: Context,
sync: Boolean = true,
profileFields: Map<String, Any?>? = null,
customFields: Map<String, Any?>? = null,
cats: List<CategoryData>? = null,
replace: Boolean? = null,
skipTriggers: Boolean? = null
): Unit

Subscription status change functions:

  • fun pushSubscribe() — subscribes to push notifications;
  • fun pushUnSubscribe() — cancels the push subscription;
  • fun pushSuspend() — suspends the push subscription (no notifications are delivered, and an unsubscribe event is not created in the user’s profile);
  • fun unSuspendPushSubscription() — used to implement LogIn/LogOut transitions.

These functions share the same signature with the following parameters:


context: Context

Required: Yes Description: Android Context.


sync: Boolean

Default: true Required: No Description: Flag that sets synchronous execution of the request.

Successful request execution:

On success, this group of functions emits an event with code 230 containing event.value, which depends on the sync flag:

If sync == true
ResponseWithHttpCode
├─ httpCode: 200
└─ response
├─ error: 0
├─ errorText: ""
└─ profile
├─ id: "your id"
├─ status: "subscribed"
├─ isTest: false
└─ subscription
├─ subscriptionId: "your subscriptionId"
├─ hashId: "7f31a9c4"
├─ provider: "android-firebase"
├─ status: "subscribed"
├─ fields
│ ├─ _os_ver: {"raw":"14","ver":"[\"14.0\", \"0.0\", \"0.0\"]"}
│ ├─ _device_type: "mob"
│ ├─ _ad_track: true
│ ├─ _device_name: "Pixel"
│ ├─ _os_language: "en"
│ ├─ _os_tz: "+0100"
│ ├─ _os: "Android"
│ ├─ _device_model: "Pixel 7"
│ └─ _app_ver: "1.0.0"
└─ cats
└─ [ { name: "developer_news", title: "dev_news", steady: false, active: false } ]

For synchronous requests, event.value["response_with_http_code"] exposes:

  • httpCode – transport status code;

  • ResponseWithProfile – a data class containing:

    • error: Int? — internal server error code (0 if no errors),

    • errorText: String? — error text (empty if no errors),

    • profile: ProfileData? — profile data if the request is successful:

      • profile info (ProfileData)
      • subscription (SubscriptionData)
      • subscription categories (CategoryData)
      • if the request fails, only profile = null will be returned
Data structures
data class ResponseWithProfile(
val error: Int?,
val errorText: String?,
val profile: ProfileData?
)

data class ProfileData(
val id: String?,
val status: String?,
val acid: String? = null,
val isTest: Boolean?,
val subscription: SubscriptionData?
)

data class SubscriptionData(
val subscriptionId: String?,
val hashId: String?,
val provider: String?,
val status: String?,
val fields: Map<String, JsonElement>?,
val cats: List<CategoryData>?
)

data class CategoryData(
val name: String?,
val title: String?,
val steady: Boolean?,
val active: Boolean?
)
If sync == false
ResponseWithHttpCode<ResponseWithProfile>
├─ httpCode: Int?
└─ response: ResponseWithProfile?
├─ error: Int?
├─ errorText: String?
└─ profile: ProfileData? = null

For asynchronous requests, event.value["response_with_http_code"] exposes:

  • httpCode – transport status code;

  • ResponseWithProfile – a data class containing:

    • error: Int? — internal server error code (0 if no errors),
    • errorText: String? — error text (empty if no errors),
    • profile: ProfileData? — profile data, always null for async requests.

Failed request execution:

If a request from this group fails, an event with one of the following codes will be emitted:

Operations without automatic retry on the SDK side:

  • 430 – notification subscription;
  • 431 — subscription suspension;
  • 432 — unsubscription.

Operations with automatic retry on the SDK side:

  • 530 – notification subscription;
  • 531 — subscription suspension;
  • 532 — unsubscription.

Event contents:

  • only httpCode if the Altcraft server was unavailable;
  • error and errorText if the server returned an error.
Reading event values
AltcraftSDK.eventSDKFunctions.subscribe { event ->
val events = setOf(
SDKEvent.PushSubscribeRequestSuccessful,
SDKEvent.PushSuspendRequestSuccessful,
SDKEvent.PushUnsubscribeRequestSuccessful,
SDKEvent.PushSubscribeRequestFailed,
SDKEvent.PushSuspendRequestFailed,
SDKEvent.PushUnsubscribeRequestFailed,
SDKEvent.PushSubscribeRetryLimit,
SDKEvent.PushEventRetryLimit,
SDKEvent.MobileEventRetryLimit
)

val sdkEvent = event.event ?: return@subscribe
if (sdkEvent !in events) return@subscribe

(event.eventValue?.get("response_with_http_code") as? ResponseWithHttpCode<ResponseWithProfile>)?.let { responseWithHttp ->
val httpCode = responseWithHttp.httpCode

val response = responseWithHttp.response
val error = response?.error
val errorText = response?.errorText

val profile = response?.profile
val profileId = profile?.id
val profileStatus = profile?.status
val profileIsTest = profile?.isTest

val subscription = profile?.subscription
val subscriptionId = subscription?.subscriptionId
val hashId = subscription?.hashId
val provider = subscription?.provider
val subscriptionStatus = subscription?.status

val fields = subscription?.fields

val cats = subscription?.cats
val firstCat = cats?.firstOrNull()
val catName = firstCat?.name
val catTitle = firstCat?.title
val catSteady = firstCat?.steady
val catActive = firstCat?.active
}
}

profileFields:Map<String, Any?>?

Default: null
Required: No
Description: A map containing profile fields.

The parameter may include system fields (e.g., _fname — first name or _lname — last name) as well as optional fields (pre-created manually in the platform UI). Allowed JSON-compatible structures:

  • Scalar values:
    • String
    • Boolean
    • Int
    • Long
    • Float
    • Double
    • null
  • Objects: Map<String, *>
  • Lists: List<*>
  • Array of maps: Array<Map<String, *>>

If an invalid optional field is passed, the request will fail with:

SDK error: 430
http code: 400
error: 400
errorText: Platform profile processing error: with field "field_name": Incorrect field

customFields:Map<String, Any?>?

Default: null Required: No Description: A map containing subscription fields.

May include system fields (e.g., _device_model — device model or _os — operating system) as well as optional fields (pre-created manually in the platform UI). Allowed value types (JSON-compatible, scalars only):

  • String
  • Boolean
  • Int
  • Long
  • Float
  • Double
  • null

If an invalid optional field is passed, the request will fail with:

SDK error: 430
http code: 400
error: 400
errorText: Platform profile processing error: field "field_name" is not valid: failed convert custom field
Note

Most subscription system fields are collected automatically by the SDK and added to push requests. These include: "_os", "_os_tz", "_os_language", "_device_type", "_device_model", "_device_name", "_os_ver", "_ad_track", "_ad_id".


cats:listOf(CategoryData)

Default: null Required: No Description: Subscription categories.

Category structure:

data class CategoryData(
val name: String?,
val title: String? = null,
val steady: Boolean? = null,
val active: Boolean?
)

When sending a push request with categories, use only the name (category name) and active (category active status) fields; other fields are not used for request processing. title and steady are populated when retrieving subscription info.

Example:

val cats = listOf(
CategoryData(name = "football", active = true),
CategoryData(name = "hockey", active = true)
)

Categories used in the request must be created beforehand and added to the resource in the Altcraft platform. If a category not present in the resource is used, the request will fail:

SDK error: 430
http code: 400
error: 400
errorText: Platform profile processing error: field "subscriptions.cats" is not valid: category not found in resource

replace:Boolean?

Default: null Required: No Description: When enabled, all subscriptions of other profiles with the same push token in the current database are set to unsubscribed after a successful request.


skipTriggers:Boolean?

Default: null Required: No Description: When enabled, the profile containing this subscription will be ignored by mailing and scenario triggers.


Request implementation examples

Example: subscribing to push notifications

Minimal working setup:

AltcraftSDK.pushSubscriptionFunctions.pushSubscribe(context)

Passing all available parameters:

AltcraftSDK.pushSubscriptionFunctions.pushSubscribe(
context = this,
sync = true,
profileFields = mapOf("_fname" to "Andrey", "_lname" to "Pogodin"),
customFields = mapOf("developer" to true),
cats = listOf(CategoryData(name = "developer_news", active = true)),
replace = false,
skipTriggers = false
)
Note

For pushSubscribe, pushSuspend, and pushUnSubscribe, the SDK automatically retries the request if the HTTP status code is in 500..599. No retry occurs for codes outside this range.


Function unSuspendPushSubscription()

The function fun unSuspendPushSubscription() is intended to implement LogIn/LogOut transitions. It works as follows:

  • searches for subscriptions with the same push token as the current one that do not belong to the profile referenced by the current JWT token;
  • changes the status of the found subscriptions from subscribed to suspended;
  • changes the status of subscriptions in the profile referenced by the current JWT from suspended to subscribed (if the JWT-referenced profile exists and contains subscriptions);
  • returns a ResponseWithHttpCode? data class in which response.profile is the current profile referenced by the JWT (if the profile does not exist, response.profile will be null).
Recommended LogIn / LogOut implementation

LogIn transition:

  • An anonymous user enters the app. The user is assigned JWT_1, pointing to database #1Anonymous.
  • A push subscription is created; the profile is created in #1Anonymous.
  • The user registers and is assigned JWT_2, pointing to database #2Registered.
  • Call unSuspendPushSubscription() — the anonymous user’s subscription in #1Anonymous is suspended.
  • Search the profile in #2Registered to restore the subscription.
  • Since a subscription with this push token does not exist in #2Registered, unSuspendPushSubscription() returns null.
  • After receiving null, call pushSubscribe() to create a new profile in #2Registered.

LogOut transition:

  • The user logs out in the app (LogOut).
  • The user is assigned JWT_1, pointing to database #1Anonymous.
  • Call unSuspendPushSubscription(), which will suspend the subscription in #2Registered and set the subscription status in #1Anonymous to subscribed.
  • The request returns #1Anonymous != null — the subscription already exists; no new one is required.

Example:

private suspend fun unSuspend(context: Context, logIn: Boolean) {

// Change JWT before the request
setAuth(context, logIn)

AltcraftSDK.pushSubscriptionFunctions
.unSuspendPushSubscription(context)
?.let { result ->
if (result.httpCode == 200 && result.response?.profile?.subscription == null) {
AltcraftSDK.pushSubscriptionFunctions.pushSubscribe(
context = context
// Specify required params
)
}
}
}

fun logIn(context: Context) = CoroutineScope(Dispatchers.IO).launch { unSuspend(context, true) }
fun logOut(context: Context) = CoroutineScope(Dispatchers.IO).launch { unSuspend(context, false) }

Getting a subscription status​

AltcraftSDK
└── val pushSubscriptionFunctions: PublicPushSubscriptionFunctions
// Status of the profile's latest subscription
├── suspend fun getStatusOfLatestSubscription(
│ context: Context
│ ): ResponseWithHttpCode<ResponseWithProfile>?
// Status for the current token/provider
├── suspend fun getStatusForCurrentSubscription(
│ context: Context
│ ): ResponseWithHttpCode<ResponseWithProfile>?
// Status of the latest subscription for the given provider (if null — current provider is used)
└── suspend fun getStatusOfLatestSubscriptionForProvider(
context: Context,
provider: String? = null
): ResponseWithHttpCode<ResponseWithProfile>?

Subscription status request functions:

  • fun getStatusOfLatestSubscription() — status of the profile’s latest subscription;
  • fun getStatusOfLatestSubscriptionForProvider() — status for the current token/provider;
  • fun getStatusForCurrentSubscription() — status of the latest subscription by provider. If null is passed, the current provider is used.

suspend fun getStatusOfLatestSubscription(context: Context): ResponseWithHttpCode<ResponseWithProfile>?

Retrieves the status of the profile's latest subscription. Returns a ResponseWithHttpCode object containing response?.profile?.subscription — the latest subscription created in the profile. If no such subscription exists, null is returned.

Usage example:

AltcraftSDK.pushSubscriptionFunctions.getStatusOfLatestSubscription(context)

suspend fun getStatusForCurrentSubscription(context: Context): ResponseWithHttpCode<ResponseWithProfile>?

Retrieves the status for the current token/provider. Returns a ResponseWithHttpCode object containing response?.profile?.subscription — the subscription found by the current push token and provider. If no such subscription exists, null is returned.

Usage example:

AltcraftSDK.pushSubscriptionFunctions.getStatusForCurrentSubscription(context)

suspend fun getStatusOfLatestSubscriptionForProvider(context: Context, provider: String? = null): ResponseWithHttpCode<ResponseWithProfile>?

Retrieves the latest subscription status by provider. Returns a ResponseWithHttpCode object containing response?.profile?.subscription — the latest subscription created with the specified push provider. If the provider is not specified (provider = null), the current token's provider is used. If no such subscription exists, null is returned.

AltcraftSDK.pushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(context, provider = null)

Below is an example of extracting profile, subscription, and category data from a status response. This approach applies to all status-fetching functions:

Data from status functions
CoroutineScope(Dispatchers.IO).launch {
AltcraftSDK.pushSubscriptionFunctions
.getStatusForCurrentSubscription(this@App)
?.let { it ->
val httpCode = it.httpCode
val response = it.response
val error = response?.error
val errorText = response?.errorText
val profile = response?.profile
val subscription = profile?.subscription
val cats = subscription?.cats
}
}

Managing provider push tokens​


AltcraftSDK
└── val pushTokenFunctions: PublicPushTokenFunctions
|
// Save a token manually (onNewToken)
├── fun setPushToken(context: Context, provider: String?, token: String?): Unit
|
// Get current device token data
├── suspend fun getPushToken(context: Context): TokenData?
|
// Set Firebase Cloud Messaging provider (null — remove)
├── fun setFCMTokenProvider(provider: FCMInterface?): Unit
|
// Set Huawei Mobile Services provider (null — remove)
├── fun setHMSTokenProvider(provider: HMSInterface?): Unit
|
// Set RuStore provider (null — remove)
├── fun setRuStoreTokenProvider(provider: RustoreInterface?): Unit
|
// Delete the push token for the specified provider
├── fun deleteDeviceToken(context: Context, provider: String, complete: () -> Unit): Unit
|
// Force token refresh (delete —> refresh)
├── fun forcedTokenUpdate(context: Context, complete: () -> Unit): Unit
|
// Change provider priority list and trigger token refresh
└── suspend fun changePushProviderPriorityList(context: Context, priorityList: List<String>): Unit

SDK functions for working with a provider token:

  • fun setPushToken() — manually set the device push token and provider in SharedPreferences;
  • fun getPushToken() — get the current push token;
  • fun setFCMTokenProvider() — set or clear the FCM push token;
  • fun setHMSTokenProvider() — set or clear the HMS push token;
  • fun setRuStoreTokenProvider() — set or clear the RuStore push token;
  • fun changePushProviderPriorityList() — dynamically switch provider and refresh the subscription’s push token;
  • fun deleteDeviceToken() — delete the push token of the specified provider;
  • fun forcedTokenUpdate() — delete the current push token and then refresh it.

fun setPushToken(context: Context, provider: String?, token: String?): Unit

Used to manually set the device push token and provider. Should be called in the push provider service's onNewToken(). Serves as a simplified way to pass the token to the SDK without implementing provider interfaces.

Using this function to pass the token is not recommended. The recommended approach is to implement FCMInterface, HMSInterface, or APNSInterface.

Usage example:

AltcraftSDK.pushTokenFunctions.setPushToken(context, provider, token)

Example of passing a token in FCMService.onNewToken():

class FCMService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)

// Pass the new token manually
AltcraftSDK.pushTokenFunctions.setPushToken(this, FCM_PROVIDER, token)
}

override fun onDeletedMessages() {}

override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
AltcraftSDK.PushReceiver.takePush(this@FCMService, message.data)
}
}

suspend fun getPushToken(context: Context): TokenData?

The function returns the current device push-token data and its provider as the data class TokenData(val provider: String, val token: String). If the token is unavailable, null will be returned.

Usage example:

AltcraftSDK.pushTokenFunctions.getPushToken(context)

Example of a push token data request:

CoroutineScope(Dispatchers.IO).launch {
AltcraftSDK.pushTokenFunctions.getPushToken(context).let {
val provider = it?.provider
val token = it?.token
}
}

fun setFCMTokenProvider(provider: FCMInterface?): Unit

Sets or removes the Firebase Cloud Messaging push-token provider. To disable the provider, pass null.

Usage example:

AltcraftSDK.pushTokenFunctions.setFCMTokenProvider(FCMProvider())
Important

Call setFCMTokenProvider() in Application.onCreate() before calling AltcraftSDK.initialization(). This guarantees registration at the start of the app process, regardless of the lifecycle state and whether the app is running in the foreground or background.


fun setHMSTokenProvider(provider: HMSInterface?): Unit

Sets or removes the Huawei Mobile Services push-token provider. To disable the provider, pass null.

Usage example:

AltcraftSDK.pushTokenFunctions.setHMSTokenProvider(HMSProvider())
Important

Call setHMSTokenProvider() in Application.onCreate() before calling AltcraftSDK.initialization(). This guarantees registration at the start of the app process, regardless of the lifecycle state and whether the app is running in the foreground or background.


fun setRuStoreTokenProvider(provider: RustoreInterface?): Unit

Sets or removes the RuStore push-token provider. To disable the provider, pass null.

Usage example:

AltcraftSDK.pushTokenFunctions.setRuStoreTokenProvider(RuStoreProvider())
Important

Call setRuStoreTokenProvider() in Application.onCreate() before calling AltcraftSDK.initialization(). This guarantees registration at the start of the app process, regardless of the lifecycle state and whether the app is running in the foreground or background.


suspend fun changePushProviderPriorityList(context: Context, priorityList: List<String>): Unit

Allows dynamic switching of the push provider with subscription token refresh. Pass a new list with a different provider order, for example: listOf(HMS_PROVIDER, RUSTORE_PROVIDER, FCM_PROVIDER).

AltcraftSDK.pushTokenFunctions.changePushProviderPriorityList(context, listOf(HMS_PROVIDER, RUSTORE_PROVIDER, FCM_PROVIDER))

fun deleteDeviceToken(context: Context, provider: String, complete: () -> Unit): Unit

Deletes the push token for the specified provider. The token is invalidated and removed from the device's local cache and from the push-provider's server. After deletion, a new token can be requested.

AltcraftSDK.pushTokenFunctions.deleteDeviceToken(context, provider) {
// callback after deletion
}

fun forcedTokenUpdate(context: Context, complete: () -> Unit): Unit

Deletes the current push token and then refreshes it.

Usage example:

AltcraftSDK.pushTokenFunctions.forcedTokenUpdate(context) {
// callback after update
}

suspend fun deleteDeviceToken(context: Context, provider: String, complete: () -> Unit): Unit

Deletes the push token for the specified provider. The token is invalidated and removed from the device’s local cache and from the push-provider’s server. After deletion, a new token can be requested.

// Delete the push token for the given provider (invalidate locally and on the server)
AltcraftSDK.pushTokenFunctions.deleteDeviceToken(context, provider) {
// callback after deletion
}

fun forcedTokenUpdate(context: Context, complete: () -> Unit): Unit

Deletes the current push token and then refreshes it.

Usage example:

// Force token refresh (delete —> update)
AltcraftSDK.pushTokenFunctions.forcedTokenUpdate(context) {
// callback after update
}

Example of provider registration​

We do not recommend using the setPushToken function to set a push token manually. Instead, configure token retrieval functions separately for each provider you use. Below is an example implementation of this approach:

Recommended provider registration method
class App : Application() {
override fun onCreate() {
super.onCreate()

// initialize RuStore provider
RuStorePushClient.init(this, "rustore project id")

// set JWT provider
AltcraftSDK.setJWTProvider(JWTProvider(applicationContext))

// set FCM provider
AltcraftSDK.pushTokenFunctions.setFCMTokenProvider(FCMProvider())

// set HMS provider
AltcraftSDK.pushTokenFunctions.setHMSTokenProvider(HMSProvider())

// set RuStore provider
AltcraftSDK.pushTokenFunctions.setRuStoreTokenProvider(RuStoreProvider())

// create AltcraftConfiguration
val config = AltcraftConfiguration.Builder(
apiUrl = "your api url",
R.drawable.ic_altcraft_label
).build()

// initialize SDK
AltcraftSDK.initialization(context = this@App, configuration = config)
}
}

Passing push notifications to the SDK​


PushReceiver is a public class that contains the function that accepts notifications.

AltcraftSDK
└── open class PushReceiver
// Incoming push handling
├── open suspend fun pushHandler(
│ context: Context,
│ message: Map<String, String>
│ ): Unit
// SDK entry point for push delivery
└── companion object
└── fun takePush(
context: Context,
message: Map<String, String>
): Unit

Functions for passing push notifications to the SDK:

  • fun takePush() — accepts notifications in the push providers’ service for further processing on the SDK side;
  • fun pushHandler() — launches the standard Altcraft push-notification handling mechanism in the SDK.

Receiving a notification​

fun takePush(context: Context, message: Map<String, String>): Unit

Accepts push notifications for further processing on the SDK side.

Usage example:

   override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)

AltcraftSDK.PushReceiver.takePush(this@FCMService, message.data)
}
// message.data — message payload

Handling a notification​

open suspend fun pushHandler(context: Context, message: Map<String, String>): Unit

Starts the standard Altcraft push-notification handling mechanism in the SDK.


Receiving notifications in any app package (optional)​

To receive notifications in any application package, do the following:

Step 1. Create an AltcraftPushReceiver class extending PushReceiver. Override the pushHandler() function in this class:

import android.content.Context
import androidx.annotation.Keep
import com.altcraft.sdk.AltcraftSDK

@Keep
class AltcraftPushReceiver : AltcraftSDK.PushReceiver() {
override suspend fun pushHandler(context: Context, message: Map<String, String>) {
// standard processing of push messages and displaying notifications
super.pushHandler(context, message)
}
}
Note

The class must be named AltcraftPushReceiver. If you name it differently, the SDK will not be able to find it to deliver the notification.


Step 2. Depending on your business goals, configure the logic of the AltcraftPushReceiver class:

  • If you want the SDK to handle and display notifications:

    • use super.pushHandler(context, message).
  • If you want to handle notifications yourself:

    • do not call super.pushHandler();
    • manually register open events using the openEvent() function; otherwise, it will not be registered by the Altcraft platform.

"deliveryEvent" delivery events are registered automatically. Creating AltcraftPushReceiver classes does not affect the registration of this event.

Note

If you created multiple AltcraftPushReceiver classes, calling super.pushHandler() in each of them will display a message to the user. To avoid duplicate notifications, call super.pushHandler() in only one class.


Step 3. Add the package names that contain AltcraftPushReceiver classes to the pushReceiverModules configuration parameter. After that, the SDK will automatically detect the presence of AltcraftPushReceiver classes in the specified packages via reflection.

If the application code will be obfuscated, the class must be annotated with @Keep or added to the R8/ProGuard rules, otherwise the SDK will not be able to discover it.

Example of adding a package to the pushReceiverModules parameter:

pushReceiverModules = listOf(
context.packageName, // application package
"com.altcraft.altcraftmobile.test"
)

Mobile Events​

// Function of the PublicMobileEventFunctions object

AltcraftSDK
└── val mobileEventFunctions: PublicMobileEventFunctions

// Send a mobile event to the server
└── fun mobileEvent(
context: Context,
sid: String,
eventName: String,
sendMessageId: String? = null,
payload: Map<String, Any?>? = null,
matching: Map<String, Any?>? = null,
matchingType: String? = null,
profileFields: Map<String, Any?>? = null,
subscription: Subscription? = null,
utm: UTM? = null
): Unit

Case: Transferring advertising campaign information

Information about the app advertising campaign that led to the installation can be sent to the platform as values of the profileFields / customFields parameters of the pushSubscribe function, as well as the utm or payload parameters of the mobileEvent() function. After receiving a UTM tag in the app as a string, you need to call the mobileEvent() function:

Transfer via payload

AltcraftSDK.mobileEventFunctions.mobileEvent(
this,
sid = "your sid",
eventName = "app_install",
payload = mapOf("utm" to "your utm tag")
)


Transfer to UTM fields

AltcraftSDK.mobileEventFunctions.mobileEvent(
this,
sid = "your sid",
eventName = "app_install",
utm = DataClasses.UTM(
campaign = "your campaign utm",
content = "your content utm",
keyword = "your keyword utm",
medium = "your medium utm",
source = "your source utm",
temp = "your temp utm"
)
)


Transfer to a custom profile field

// transfer a UTM tag to a profile field
// profile fields must be created in the platform in advance
AltcraftSDK.shared.pushSubscriptionFunctions.pushSubscribe(
profileFields: ["utm": "your utm tag"]
)


Data sent using any of these methods can be used to create a segment in the platform.

To register a mobile event, use the mobileEvent() function. It has the following parameters:


context: Context

Required: Yes
Description: Android Context.


sid: String

Required: Yes
Description: String identifier of the pixel to which mobile events are linked.


eventName: String

Required: Yes
Description: The name of the mobile event.


sendMessageId: String?

Required: No
Description: SMID identifier of the sent message (if the event is associated with a specific mailing).


payload: String

Required: No
Description: Event data — a map with string keys and values, where only scalar data types are allowed:

  • String
  • Boolean
  • Int
  • Long
  • Float
  • Double
  • null

matching: Map<String, Any?>?

Required: No
Description: A map for passing values with matching types and identifiers.


matchingType: String?

Required: No
Description: The type of matching.


profileFields: Map<String, Any?>?

Required: No
Description: Profile fields — a map with string keys and JSON-compatible values:

  • Scalar values:

    • String
    • Boolean
    • Int
    • Long
    • Float
    • Double
    • null
  • Objects: Map<String, *>

  • Lists: List<*>

  • Arrays of maps: Array<Map<String, *>>

Note

This parameter is used only when working with JWT authorization.



utm: UTM?

Required: No
Description: UTM tags. Added using the UTM data class, where each UTM type is a separate parameter.

data class UTM (
val campaign: String? = null,
val content: String? = null,
val keyword: String? = null,
val medium: String? = null,
val source: String? = null,
val temp: String? = null
)


subscription: Subscription?

Required: No
Description: Parameter for adding a subscription for a selected channel.

Possible values are implementations (subtypes) of the sealed interface Subscription:

  • EmailSubscription — email subscription
  • SmsSubscription — SMS subscription
  • PushSubscription — push subscription
  • CcDataSubscription — subscription in Telegram, WhatsApp, Viber, or Notify.
Note

Used only when working with JWT authorization.



Implementations of the Subscription interface​

General model: Subscription

Purpose — base (sealed) interface for all types of subscriptions. Serialization is polymorphic, with the discriminator field channel.

Common fields (for all implementations):

FieldTypeRequiredDescription
resource_idIntYesIdentifier of the subscription resource/source
statusString?NoSubscription status (e.g., active/suspended)
priorityInt?NoDelivery priority for the subscription
custom_fieldsMap<String, Any?>?NoCustom fields (key–value) for extended segmentation
catsList<String>?NoSubscription categories
channelStringYesChannel type; defined by the implementation


Subscription types:

EmailSubscription (channel = "email")

Required fields

FieldTypeRequiredDescription
resourceIdIntYesAltcraft resource ID
emailStringYesRecipient email address

Optional fields

FieldTypeRequiredDescription
statusStringNoSubscription status
priorityIntNoSubscription priority
customFieldsMap<String, Any?>NoStandard and custom subscription fields
catsList<String>NoSubscription categories

SmsSubscription (channel = "sms")

Required fields

FieldTypeRequiredDescription
resourceIdIntYesAltcraft resource ID
phoneStringYesPhone number in international format

Optional fields

FieldTypeRequiredDescription
statusStringNoSubscription status
priorityIntNoSubscription priority
customFieldsMap<String, Any?>NoStandard and custom subscription fields
catsList<String>NoSubscription categories

PushSubscription (channel = "push")

Required fields

FieldTypeRequiredDescription
resourceIdIntYesAltcraft resource ID
providerStringYesProvider (e.g., "android-firebase")
subscriptionIdStringYesUnique subscription identifier from the provider

Optional fields

FieldTypeRequiredDescription
statusStringNoSubscription status
priorityIntNoSubscription priority
customFieldsMap<String, Any?>NoStandard and custom subscription fields
catsList<String>NoSubscription categories

CcDataSubscription (channel ∈ {"telegram_bot","whatsapp","viber","notify"})

Required fields

FieldTypeRequiredDescription
resourceIdIntYesAltcraft resource ID
channelStringYesOne of: "telegram_bot", "whatsapp", "viber", "notify"
ccDataJsonObjectYesChannel-specific data (e.g., chat ID, phone number, tokens)

Optional fields

FieldTypeRequiredDescription
statusStringNoSubscription status
priorityIntNoSubscription priority
customFieldsMap<String, Any?>NoStandard and custom subscription fields
catsList<String>NoSubscription categories

Profile Fields Update​


Important

Updating profile fields with the updateProfileFields() function works only when using JWT authorization for SDK API requests.

AltcraftSDK
└── val profileFunctions: PublicProfileFunctions
// Updates Altcraft profile fields
└── fun updateProfileFields(
context: Context,
profileFields: Map<String, Any?>? = null,
skipTriggers: Boolean? = null
): Unit

To update profile fields, use the updateProfileFields() function. It has the following parameters:


context: Context

Required: Yes
Description: Android Context.


profileFields: Map<String, Any?>?

Required: No
Description: Profile fields — a map containing the values for the fields that need to be updated (JSON-compatible types):

  • Scalar values:

    • String
    • Boolean
    • Int
    • Long
    • Float
    • Double
    • null
  • Objects: Map<String, *>

  • Lists: List<*>

  • Array of maps: Array<Map<String, *>>

Note

For the update to succeed, the fields must have been previously added to the subscriber's profile.


skipTriggers: Boolean?

Default: null
Required: No
Description: When enabled, the profile containing this subscription will be ignored in mailing triggers and scenarios.


Receiving SDK Events in the Application​


// Functions of the Events object

AltcraftSDK
└── val eventSDKFunctions: Events
// Subscribe to SDK events (replaces the existing subscriber)
├── fun subscribe(
│ newSubscriber: (Event) -> Unit
│ ): Unit
// Unsubscribe from events
└── fun unsubscribe(): Unit

The application can have only one active subscriber to SDK events.


Event Subscription​

fun subscribe(newSubscriber: (Event) -> Unit): Unit

Used to subscribe and receive SDK events in the application. When an SDK event occurs, it calls the callback and passes an instance of the Event class (or one of its subclasses).

Usage example:

AltcraftSDK.eventSDKFunctions.subscribe { event ->
// Handle event
}

All events provided by the SDK are instances of Event or its subclasses:

  • Event — general event (info, successful requests);
  • Error — error event;
  • RetryError — error event for a request that will be automatically retried by the SDK.

Each event contains the following fields:

  • function — the name of the function that triggered the event;
  • event — SDK event type, represented by an SDKEvent enum value (see "SDK Events" for the full list);
  • eventMessage — event message;
  • eventValue — arbitrary [String: Any?]? data passed as event payload;
  • date — timestamp of the event;
  • internal — flag indicating whether the event is internal.
SDK Event classes
open class Event(
val function: String,
val event: SDKEvent? = null,
val eventMessage: String? = null,
val eventValue: Map<String, Any?>? = null,
val date: Date = Date(),
val internal: Boolean = false
)

open class Error(
function: String,
event: SDKEvent? = null,
eventMessage: String? = null,
eventValue: Map<String, Any?>? = null,
date: Date = Date(),
) : Event(function, event, eventMessage, eventValue, date)

class RetryError(
function: String,
event: SDKEvent? = null,
eventMessage: String? = null,
eventValue: Map<String, Any?>? = null,
date: Date = Date(),
) : Error(function, event, eventMessage, eventValue, date)
Example of a successful push subscription event
├─ function: processResponse
├─ event: PushSubscribeRequestSuccessful
├─ eventMessage: "successful request: push/subscribe"
├─ eventValue
│ ├─ http code: 200
│ └─ response
│ ├─ error: 0
│ ├─ errorText: ""
│ └─ profile
│ ├─ id: "your id"
│ ├─ status: "subscribed"
│ ├─ acid: "your acid"
│ ├─ isTest: false
│ └─ subscription
│ ├─ subscriptionId: "your subscriptionId"
│ ├─ hashId: "c52b28d2"
│ ├─ provider: "android-firebase"
│ ├─ status: "subscribed"
│ ├─ fields
│ │ ├─ _device_name: "Pixel 7"
│ │ ├─ _device_model: "Google Pixel 7"
│ │ ├─ _os_tz: "+0300"
│ │ ├─ _os_language: "ru"
│ │ ├─ _os_ver: {"raw":"14","ver":[14]}
│ │ ├─ _ad_track: true
│ │ ├─ _os: "Android"
│ │ └─ _device_type: "mob"
│ └─ cats
│ └─ [ { name: "developer_news", title: "dev_news", steady: false, active: false } ]
└─ date: 2025-09-03 09:01:44 +0000

Unsubscribing from events​

fun unsubscribe(): Unit

This function unsubscribes from SDK events. It stops event delivery while keeping the callback assigned.

Usage example:

// Unsubscribe from SDK events
AltcraftSDK.eventSDKFunctions.unsubscribe()

List of all SDK events​

SDKEvent enum event list

SDK events are represented by the SDKEvent enum class, where each value contains a string message (message).

General SDK events:

ValueMessage
ConfigIsSetSDK configuration is installed
PushProviderSetpush provider set:
NotAcPushreceived a notification unrelated to the Altcraft Platform
AcPushreceived Altcraft push notification
PushIsPostedpush is posted
SdkClearedSDK data has been cleared
ReceiverRedefinedreceiver is redefined
NotAuthenticatedErrorUser is not authenticated
UserLogOutUser logged out. Anonymous session started.

Internal errors without retry:

ValueMessage
ConfigIsNotSetthe configuration is not set
ConfigNotValidinvalid configuration
SdkInitWaitingExpiredSDK initialization timeout has expired
MobileEventPartsIsNullmobile event parts is null
InvalidPushProviderinvalid provider. Available - android-firebase, android-huawei, android-rustore.
PushDataIsNullpush data is null
PushUidIsNulluid in the push data is null or empty, it is impossible to send a push event to the server.
ErrorImgLoaderror uploading the notification image
NotificationErrcouldn't create notification
ChannelNotCreatedthe notification channel has not been created
SmidIsNullsend message ID is null
InvalidStaticFieldinvalid in-app static field
RoomMigrationErrorRoom database migration failed. The local SDK database will be recreated.

Missing request payload (without retry):

ValueMessage
UnSuspendRequestDataIsNullunsuspend request data is null
SubscriptionStatusRequestDataIsNullstatus request data is null
InAppSubscriptionStatusRequestDataIsNullstatus request data is null
AuthorizeRequestDataIsNullauthorize request data is null

Retry limit reached:

ValueMessage
PushSubscribeRetryLimitpush subscribe retry limit
PushEventRetryLimitpush event retry limit
MobileEventRetryLimitmobile event retry limit
ProfileUpdateRetryLimitprofile update retry limit
InAppSubscribeRetryLimitin-app subscribe retry limit
AuthRequestRetryLimitauth request retry limit
InAppEventRetryLimitin-app event retry limit

SDK or environment state issues:

ValueMessage
ConfigIsNullconfig data is null
PushTokenIsNullcurrent push token is null
UserTagIsNulluserTag is null. It is impossible to identify the user
PermissionDeniedno permission to send notifications
NoInternetConnectno internet connection, retry when connection is restored
NotUpdatedfailed to update the push token. The subscription request was rejected
ResponseDataIsNullresponse data is null
JwtTokenIsNullJWT token is null
MatchingIsNullmatching mode is null
JwtTooLargeJWT payload exceeds allowed size (16 KB limit): input rejected to prevent DoS
PayloadIsMissingJWT does not contain a payload
InternalAuthIsNullinternal auth data is null
ExternalAuthIsNullexternal auth data is null
MatchingIdIsNullmatching claim does not contain a matching ID
InvalidPayloadinvalid mobile event payload: not all values are primitives
InvalidCustomFieldsinvalid custom fields: not all values are primitives

Missing request payload (with retry):

ValueMessage
PushSubscribeRequestDataIsNullpush subscribe request data is null
TokenUpdateRequestDataIsNulltoken update request data is null
PushEventRequestDataIsNullpush event request data is null
InAppEventRequestDataIsNullin-app event request data is null
MobEventRequestDataIsNullmobile event request data is null
ProfileUpdateRequestDataIsNullprofile update request data is null
InAppSubscribeRequestDataIsNullprofile update request data is null
InAppPlacementsRequestDataIsNullin-app placements request data is null

Successful API requests:

ValueMessage
PushUnsubscribeRequestSuccessfulsuccessful request: push/unsubscribe
PushSubscribeRequestSuccessfulsuccessful request: push/subscribe
PushSuspendRequestSuccessfulsuccessful request: push/suspend
InAppUnsubscribeRequestSuccessfulsuccessful request: inapp/unsubscribe
InAppSubscribeRequestSuccessfulsuccessful request: inapp/subscribe
InAppStatusRequestSuccessfulsuccessful request: inapp/status
InAppEventRequestSuccessfulsuccessful request: inapp/event
InAppPlacementsRequestSuccessfulsuccessful request: in_app/placements
PushStatusRequestSuccessfulsuccessful request: push/status
TokenUpdateRequestSuccessfulsuccessful request: push/update
PushEventRequestSuccessfulsuccessful request: event/push
MobileEventRequestSuccessfulsuccessful request: event/post
UnsuspendRequestSuccessfulsuccessful request: push/unsuspend
ProfileUpdateRequestSuccessfulsuccessful request: profile/update
AuthenticateSuccessfulsuccessful request: profile/authenticate

Failed API requests:

ValueMessage
PushUnsubscribeRequestFailedfailed request: push/unsubscribe
PushSubscribeRequestFailedfailed request: push/subscribe
PushSuspendRequestFailedfailed request: push/suspend
InAppUnsubscribeRequestFailedfailed request: inapp/unsubscribe
InAppSubscribeRequestFailedfailed request: inapp/subscribe
InAppStatusRequestFailedfailed request: inapp/status
InAppEventRequestFailedfailed request: inapp/event
InAppPlacementsRequestFailedfailed request: in_app/placements
PushStatusRequestFailedfailed request: push/status
TokenUpdateRequestFailedfailed request: push/update
PushEventRequestFailedfailed request: event/push
MobileEventRequestFailedfailed request: event/post
ProfileUpdateRequestFailedfailed request: profile/update
UnsuspendRequestFailedfailed request: push/unsuspend
AuthenticateFailedfailed request: profile/authenticate
InAppStaticErrorLoaderror loading in-app notification static resources
InAppContentErrorLoaderror loading in-app notification content

In-App Notifications​


AltcraftSDK
└── val inAppFunctions: PublicInAppFunctions
// Configure In-App notification animation
├── fun setAnimation(block: Animator.() -> Unit): Unit
//
// Set current screen marker (used for In-App notification filtering)
├── fun setScreen(screen: String): Unit
//
// Custom In-App notification trigger by name
├── fun inAppTrigger(context: Context, name: String): Unit
//
// Request available In-App placements
├── fun getInAppPlacements(context: Context): Unit
//
// Subscribe to Activity lifecycle for automatic In-App display
├── fun subscribeOnActivityLifecycle(context: Context): Unit
//
// Subscribe to In-App notifications (status = SUBSCRIBED)
├── fun inAppSubscribe(
│ context: Context,
│ sync: Boolean = true,
│ profileFields: Map<String, Any?>? = null,
│ customFields: Map<String, Any?>? = null,
│ cats: List<CategoryData>? = null,
│ replace: Boolean? = null,
│ skipTriggers: Boolean? = null
│ ): Unit
//
// Unsubscribe from In-App notifications (status = UNSUBSCRIBED)
├── fun inAppUnSubscribe(
│ context: Context,
│ sync: Boolean = true,
│ profileFields: Map<String, Any?>? = null,
│ customFields: Map<String, Any?>? = null,
│ cats: List<CategoryData>? = null,
│ replace: Boolean? = null,
│ skipTriggers: Boolean? = null
│ ): Unit
//
// In-App notification subscription status
└─ suspend fun getInAppSubscriptionStatus(context: Context): ResponseWithHttpCode<ResponseWithProfile>?

Functions for working with In-App notifications:

  • fun setAnimation() — configure In-App notification display animation;
  • fun setScreen() — set current screen marker, used for In-App notification filtering;
  • fun inAppTrigger() — trigger custom In-App notification by name;
  • fun getInAppPlacements() — request available In-App placements from the server;
  • fun subscribeOnActivityLifecycle() — subscribe to Activity lifecycle for automatic In-App notification display;
  • fun inAppSubscribe() — subscribe to In-App notifications;
  • fun inAppUnSubscribe() — unsubscribe from In-App notifications;
  • suspend fun getInAppSubscriptionStatus() — get In-App notification subscription status.

fun setAnimation(block: Animator.() -> Unit): Unit

Allows configuring custom animation for In-App notification display. Accepts an extension function on Animator where animation parameters can be set.

Usage example:

AltcraftSDK.inAppFunctions.setAnimation {
// animation configuration
}

fun setScreen(screen: String): Unit

Sets the current screen marker. The marker value is used by the Altcraft platform for In-App notification filtering — allows displaying notifications only on specific app screens.

Call this function when navigating to a new screen so the SDK always knows which screen the user is on.

Usage example:

AltcraftSDK.inAppFunctions.setScreen("home_screen")

fun inAppTrigger(context: Context, name: String): Unit

Manually triggers the display of an In-App notification by name. Used for custom triggers when a notification needs to be shown in response to a user action or app event.

Usage example:

AltcraftSDK.inAppFunctions.inAppTrigger(context, "my_custom_trigger")

fun getInAppPlacements(context: Context): Unit

Requests available In-App placements from the Altcraft server. The request result can be retrieved via SDK events.

Usage example:

AltcraftSDK.inAppFunctions.getInAppPlacements(context)

fun subscribeOnActivityLifecycle(context: Context): Unit

Subscribes the SDK to the Activity lifecycle for automatic In-App notification display. Upon registration, the SDK starts tracking Activity lifecycle events and automatically displays In-App notifications when the app comes to the foreground.

Important

Call subscribeOnActivityLifecycle() as early as possible at app startup — in Application.onCreate(). This is necessary so that the Activity lifecycle callback is registered before the first foreground transition. If the call is delayed, In-App notifications that should have been displayed at app launch may be missed.

Usage example:

class App : Application() {
override fun onCreate() {
super.onCreate()

// Register as early as possible
AltcraftSDK.inAppFunctions.subscribeOnActivityLifecycle(this)

// Remaining initialization
}
}

fun inAppSubscribe(context: Context, ...): Unit

Subscribes to In-App notifications. After a successful call, the user's profile will be subscribed to receive In-App notifications from the Altcraft platform.

Function parameters are the same as pushSubscribe():

  • context — Android Context;
  • sync — synchronous execution flag;
  • profileFields — profile fields;
  • customFields — subscription fields;
  • cats — subscription categories;
  • replace — when enabled, all subscriptions of other profiles with the same push token are set to unsubscribed;
  • skipTriggers — when enabled, the profile will be ignored by mailing and scenario triggers.

Parameters are configured exactly the same way as in pushSubscribe().

Usage example:

AltcraftSDK.inAppFunctions.inAppSubscribe(context)

fun inAppUnSubscribe(context: Context, ...): Unit

Unsubscribes from In-App notifications. After a successful call, the user's profile will be unsubscribed from In-App notifications.

Function parameters are the same as pushUnSubscribe().

Usage example:

AltcraftSDK.inAppFunctions.inAppUnSubscribe(context)

suspend fun getInAppSubscriptionStatus(context: Context): ResponseWithHttpCode<ResponseWithProfile>?

Retrieves the current In-App notification subscription status. Returns a ResponseWithHttpCode object containing response?.profile?.subscription — the current In-App subscription for the profile. If no subscription exists, null is returned.

Usage example:

CoroutineScope(Dispatchers.IO).launch {
AltcraftSDK.inAppFunctions.getInAppSubscriptionStatus(context)?.let { responseWithHttp ->
val httpCode = responseWithHttp.httpCode
val response = responseWithHttp.response
val profile = response?.profile
val subscription = profile?.subscription
}
}

Authentication​


AltcraftSDK
└── val authFunctions: PublicAuthFunctions
// Authenticate user
├── fun authenticate(context: Context): Unit
//
// Log out user
├── fun logOut(context: Context): Unit
//
// Check authentication status
└─ suspend fun isAuthenticated(context: Context): Boolean

Functions for user authentication:

  • fun authenticate() — authenticate the user on the Altcraft platform;
  • fun logOut() — log out the user, end session;
  • suspend fun isAuthenticated() — check current authentication status.

fun authenticate(context: Context): Unit

Authenticates the user on the Altcraft platform. Sends a request to the server with current authentication data (JWT token or rToken) and binds the device to the user's profile.

After successful authentication, the user gains access to personalized InApp notifications.

Important

Call authenticate() only when the user actually logs into the app and is known to the client (for example, after successful authorization via login form, OAuth, or another authentication mechanism in your app).

Usage example:

AltcraftSDK.authFunctions.authenticate(context)

fun logOut(context: Context): Unit

Logs out the user — ends the current authentication session on the Altcraft platform. After calling, the device switches to anonymous session mode. In this mode, personalized InApp notifications are unavailable, as well as subscription management via inAppSubscribe().

Important

Call logOut() only when the user actually logs out of the app and switches to anonymous mode.

Usage example:

AltcraftSDK.authFunctions.logOut(context)

suspend fun isAuthenticated(context: Context): Boolean

Checks the current user authentication status. Returns true if the user is successfully authenticated on the Altcraft platform, and false otherwise.

Usage example:

CoroutineScope(Dispatchers.IO).launch {
val authenticated = AltcraftSDK.authFunctions.isAuthenticated(context)
if (authenticated) {
// user is authenticated
} else {
// user is not authenticated
}
}

Additional SDK Functions​


Manual Push Event Registration​

Note

These functions are only used if you implement your own notification handling logic and do not pass them to the Altcraft SDK. By default, the Altcraft SDK automatically processes notifications, so these methods are only required when you need custom client-side handling.

// Functions of the PublicPushEventFunctions object

AltcraftSDK
└── val pushEventFunctions: PublicPushEventFunctions

// Register Altcraft push delivery (triggers delivery event)
├── fun deliveryEvent(
│ context: Context,
│ message: Map<String, String>? = null,
│ messageUID: String? = null
│ ): Unit

// Register Altcraft push open (triggers open event)
└── fun openEvent(
context: Context,
message: Map<String, String>? = null,
messageUID: String? = null
): Unit

Manual event registration functions:

  • fun deliveryEvent() — registers push delivery;
  • fun openEvent() — registers push open.

fun deliveryEvent(context: Context, message: Map<String, String>? = null, messageUID: String? = null): Unit

Manually registers a push delivery event on the Altcraft platform. To log the event on the server, pass notification data in the message or messageUID parameter.

Usage example:

AltcraftSDK.pushEventFunctions.deliveryEvent(context, message, messageUID)

fun openEvent(context: Context, message: Map<String, String>? = null, messageUID: String? = null): Unit

Manually registers a push open event on the Altcraft platform. To log the event on the server, pass notification data in the message or messageUID parameter.

Usage example:

AltcraftSDK.pushEventFunctions.openEvent(context, message, messageUID)

Passing custom data to Intent extras when opening a push notification​

The SDK supports passing arbitrary data from a push notification to the application using the special "_extra" key. The value of _extra must be a string containing a JSON object.

When a user taps the notification, the SDK automatically:

  1. Extracts the _extra value from the push payload.
  2. Adds it to the Intent.
  3. Passes it to the Activity that handles the notification open event or deep link.

As a result, the contents of _extra become a regular Intent extra and are available in the application via:

val extraJson = intent?.getStringExtra("_extra")

The _extra field is intended for passing additional parameters that should not be included in the URL but are required when handling the notification open event.

The _extra value can be added using Custom JSON in the push notification template.


SDK Data Clearing​

fun clear(context: Context, onComplete: (() -> Unit)? = null)

This function clears all SDK data and cancels all pending background tasks. It cancels WorkManager jobs, deletes Room database entries, and clears SharedPreferences.

Usage example:

AltcraftSDK
// Full SDK data cleanup (DB, SharedPreferences, background tasks)
└── fun clear(
context: Context,
onComplete: (() -> Unit)? = null
): Unit

The function includes an optional completion parameter, which is called after cleanup and task cancellation are complete.


Functional Profile Field Update​

AltcraftSDK
└─ val pushSubscriptionFunctions: PublicPushSubscriptionFunctions
└─ fun actionField(key: String): ActionFieldBuilder

fun actionField(key: String): ActionFieldBuilder

A helper function for simplifying the functional profile field update process. It supports the following commands:

    .set(value)
.unset(value)
.incr(value)
.add(value)
.delete(value)
.upsert(value)

Usage example:

AltcraftSDK.pushSubscriptionFunctions.pushSubscribe(
context = context,
// "_fname" — field to be changed
// .set("Andrey") — command that sets the value "Andrey" for this field
// actionField().set() returns Pair<String, Map<String, Any?>>, so wrap in mapOf()
profileFields = mapOf(
AltcraftSDK.pushSubscriptionFunctions
.actionField("_fname").set("Andrey")
)
)

Resetting retry-operation restrictions during SDK initialization​

Note

When the SDK is initialized, background tasks are launched to control and retry requests related to push notifications, mobile events, and push-token update checks. Execution of this function is limited to one run within a single application process lifecycle.

In some cases, you may need to reset this restriction. In such situations, use the function:

fun unlockInitialOperationsInThisSession(): Unit

This function resets the flag that prevents background retry-control tasks from running again within the same process session.


Requesting Notification Permission​

Note

Starting from Android 13 (API 33, Tiramisu), apps must explicitly request the POST_NOTIFICATIONS permission before sending notifications. On earlier Android versions, this call is not required — the permission is granted automatically.

fun requestNotificationPermission(context: Context, activity: ComponentActivity)

Checks the current notification permission status and, if necessary, displays the system permission request dialog to the user. If the user has previously denied notifications, calling this function again will re-prompt the permission dialog.


Checking Push Notification Source​

fun isAltcraftPush(message: Map<String, String>): Boolean

A static function in the PushReceiver companion object that checks whether a push notification was sent by the Altcraft platform.

Usage example:

if (AltcraftSDK.PushReceiver.isAltcraftPush(message.data)) {
AltcraftSDK.PushReceiver.takePush(this, message.data)
}

Last updated on Jul 7, 2026
Previous
Quick Start
Next
SDK Configuration
  • Working with subscription statuses
    • Changing a subscription status
    • Getting a subscription status
  • Managing provider push tokens
    • Example of provider registration
  • Passing push notifications to the SDK
    • Receiving a notification
    • Handling a notification
    • Receiving notifications in any app package (optional)
  • Mobile Events
    • Implementations of the Subscription interface
  • Profile Fields Update
  • Receiving SDK Events in the Application
    • Event Subscription
    • Unsubscribing from events
    • List of all SDK events
  • In-App Notifications
  • Authentication
  • Additional SDK Functions
    • Manual Push Event Registration
    • Passing custom data to Intent extras when opening a push notification
    • SDK Data Clearing
    • Functional Profile Field Update
    • Resetting retry-operation restrictions during SDK initialization
    • Requesting Notification Permission
    • Checking Push Notification Source
© 2015 - 2026 Altcraft, LLC. All rights reserved.