Braze

class Braze @VisibleForTesting constructor(context: Context) : IBraze

Primary implementation of IBraze. Provides methods for tracking analytics, managing user identity, handling push notifications, Content Cards, Feature Flags, in-app messages, and other Braze SDK features.

Obtain an instance via Braze.getInstance.

Constructors

Link copied to clipboard
internal constructor(context: Context)

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
Link copied to clipboard
private lateinit var brazeUser: BrazeUser
Link copied to clipboard

Synchronously get the ContentCardsUpdatedEvent from the ContentCardsStorageProvider.

Link copied to clipboard
Link copied to clipboard
open override val currentUser: BrazeUser?

The user currently being tracked by Braze. Note that modifying values on instances of BrazeUser for a previous user will result in those values being stored locally, but they will not be synced with the Braze server until that user becomes active again.

Link copied to clipboard
open override val deviceId: String

Get the device ID - a randomly generated, app specific ID that is stored on the device. A new ID will be generated if the user clears the data for the app or removes/re-installs the app. The ID will persist across Braze.changeUser calls.

Link copied to clipboard
internal lateinit var deviceIdProvider: IDeviceIdProvider
Link copied to clipboard
internal var externalIEventMessenger: IEventMessenger
Link copied to clipboard
open override var imageLoader: IBrazeImageLoader

The IBrazeImageLoader for the Braze instance. This IBrazeImageLoader is used for all image related actions in the Braze SDK.

Link copied to clipboard
Link copied to clipboard

Should only be true when the current instance has been stopped. When true on a given instance, a new instance should be returned from Braze.getInstance.

Link copied to clipboard
private lateinit var offlineUserStorageProvider: OfflineUserStorageProvider
Link copied to clipboard
internal lateinit var pushDeliveryManager: PushDeliveryManager
Link copied to clipboard
open override var registeredPushToken: String?

The push notification registration token for this device. When set, immediately flushes the token to Braze.

Link copied to clipboard
internal lateinit var registrationDataProvider: IPushRegistrationDataProvider
Link copied to clipboard
internal lateinit var udm: IUserDependencyManager

This variable should not be used outside of this class.

Functions

Link copied to clipboard
internal fun addSerializedCardJsonToStorage(serializedCardJson: String, userId: String?)

Adds a single ContentCard to storage from its serialized JSONObject string.

Link copied to clipboard
open override fun <T> addSingleSynchronousSubscription(subscriber: IEventSubscriber<T>, eventClass: Class<T>)

Adds a new subscription for an external Braze SDK event. Note that this subscriber will be called synchronously from the running thread of the Braze SDK and may not be on the same thread as the caller of this method.

Link copied to clipboard
Link copied to clipboard

Returns true if the locally cached Content Cards have exceeded their time-to-live.

Link copied to clipboard
open override fun changeUser(userId: String?)

When a user first uses Braze on a device they are considered "anonymous". Use this method to identify a user with a unique ID, which enables the following:

open override fun changeUser(userId: String?, sdkAuthSignature: String?)

Identical to .changeUser but provides an sdk auth signature for the user before any networking begins, even if the existing external id is used.

Link copied to clipboard
open override fun closeSession(activity: Activity?)

Closes the current session. The session may be reopened if a call is made to IBraze.openSession within the session timeout.

Link copied to clipboard
Link copied to clipboard
open override fun deserializeContentCard(contentCardString: String?): Card?
open override fun deserializeContentCard(contentCardJson: JSONObject?): Card?

Constructs a Content Card from its Card.forJsonPut output. Useful for caching Content Card data and recreating them for your own purposes.

Link copied to clipboard
open override fun deserializeInAppMessageString(inAppMessageString: String?): IInAppMessage?

This function returns a deserialized in-app message from the message JSON string.

Link copied to clipboard
internal fun dismissBanner(placementId: String)
Link copied to clipboard
open override fun getAllFeatureFlags(): List<FeatureFlag>

Retrieves the offline/cached list of Feature Flags from offline storage.

Link copied to clipboard
open override fun getBanner(id: String): Banner?

Get a specific Banner by placement ID.

Link copied to clipboard
open override fun getCachedContentCards(): List<Card>?

Retrieves the offline/cached list of Content Cards from offline storage. Useful method to synchronously check the state of Content Cards already synced to the device.

Link copied to clipboard
Link copied to clipboard
open override fun getContentCardCount(): Int

Retrieves information about Content Cards based on the currently cached data.

Retrieves information about Content Cards based on the currently cached data.

Link copied to clipboard
open override fun getContentCardUnviewedCount(): Int

Retrieves information about Content Cards based on the currently cached data.

Link copied to clipboard
open override fun getCurrentUser(completionCallback: IValueCallback<BrazeUser>)

Returns the user currently being tracked by Braze. Note that modifying values on instances of BrazeUser for a previous user will result in those values being stored locally, but they will not be synced with the Braze server until that user becomes active again.

Link copied to clipboard
private fun getDeviceDataProvider(): IDeviceDataProvider
Link copied to clipboard
open override fun getDeviceIdAsync(completionCallback: IValueCallback<String>)

Get the device ID - a randomly generated, app specific ID that is stored on the device. A new ID will be generated if the user clears the data for the app or removes/re-installs the app. The ID will persist across Braze.changeUser calls.

Link copied to clipboard
open override fun getFeatureFlag(id: String): FeatureFlag?

Requests a specific Feature Flags. This will pull the data from a local cache and does not force a refresh.

Link copied to clipboard
internal fun handleInAppMessageTestPush(intent: Intent)

Requests triggers if the Intent contains extras for a test in-app message. Does nothing otherwise.

Link copied to clipboard

Requests banners refresh for internal purposes.

Link copied to clipboard
Link copied to clipboard
open override fun logBannerClick(placementId: String, buttonId: String?)

Logs a click for Banner with the placement ID. If there is no stored Banner with that placement ID, no click will be logged.

Link copied to clipboard
open override fun logBannerImpression(placementId: String): Boolean

Logs an impression for Banner with the placement ID. If there is no stored Banner with that placement ID, no impression will be logged. Banner impressions are logged only once per session.

Link copied to clipboard
open override fun logCustomEvent(eventName: String?)
open override fun logCustomEvent(eventName: String?, properties: BrazeProperties?)

Reports a custom named event.

Link copied to clipboard
open override fun logFeatureFlagImpression(id: String)

Logs an impression for Feature Flag with the provided ID. If there is no stored Feature Flag with provided ID, no impression will be logged.

Logs a location recorded event based using an IBrazeLocation. This is used for automatic location updates and respects the automatic location collection setting.

Link copied to clipboard
open override fun logPurchase(productId: String?, currencyCode: String?, price: BigDecimal?)
open override fun logPurchase(productId: String?, currencyCode: String?, price: BigDecimal?, properties: BrazeProperties?)

In order to log a purchase, switch to logPurchase. Using this method will by default log a purchase with a quantity of one.

open override fun logPurchase(productId: String?, currencyCode: String?, price: BigDecimal?, quantity: Int)

In order to log a purchase, switch to logPurchase.

open override fun logPurchase(productId: String?, currencyCode: String?, price: BigDecimal?, quantity: Int, properties: BrazeProperties?)

Reports that the current user made an in app purchase. Useful for tracking and segmenting users more likely to make purchases.

Link copied to clipboard
internal fun logPushDelivery(campaignId: String, timeInMs: Long)

Logs a push delivery event.

Link copied to clipboard
internal fun logPushMaxCampaign(campaign: String)

Logs a push campaign for PushMax.

Link copied to clipboard
open override fun logPushNotificationActionClicked(campaignId: String?, actionId: String?, actionType: String?)

Reports that the user clicked on a push notification action button.

Link copied to clipboard
open override fun logPushNotificationOpened(intent: Intent?)

Reports that the user clicked on the push notification. Note that integrations shouldn't be calling this method directly.

open override fun logPushNotificationOpened(campaignId: String?)

When possible, .logPushNotificationOpened should be used instead. Note that integrations shouldn't be calling this method directly.

Link copied to clipboard
open override fun logPushStoryPageClicked(campaignId: String?, pageId: String?)

Reports that the user clicked on a push story page.

Link copied to clipboard
open override fun openSession(activity: Activity?)

Opens a new session or resumes the previous session. A call to IBraze.openSession within the session timeout of a call to IBraze.closeSession will cause the previous session to be resumed. This is done so that transitions from one Activity to another do not create a new session each time.

Link copied to clipboard

Flushes the stored push delivery events.

Link copied to clipboard
Link copied to clipboard
private fun publishError(throwable: Throwable)
Link copied to clipboard
internal fun recordGeofenceTransition(geofenceId: String?, transitionType: GeofenceTransitionType?)

Requests the geofence manager to post a geofence transition report to Braze for the given geofence Id and transition type combination.

Link copied to clipboard
Link copied to clipboard
open override fun refreshFeatureFlags()

Requests a refresh of Feature Flags from the Braze server.

Link copied to clipboard
open override fun <T> removeSingleSubscription(subscriber: IEventSubscriber<T>?, eventClass: Class<T>)

Removes a single subscription associated with the given activity and event class. This should be called if you want to selectively unsubscribe from an event, but do not want to remove every subscription for the activity.

Link copied to clipboard
open override fun requestBannersRefresh(ids: List<String>)
open override fun requestBannersRefresh(ids: List<String>, completionCallback: IValueCallback<BannersUpdatedEvent>?)

Requests a refresh of Banners from the Braze server.

Link copied to clipboard
open override fun requestContentCardsRefresh()

Requests an immediate refresh of Content Cards from the Braze server.

Link copied to clipboard

Requests an immediate refresh of Content Cards from offline storage. Note that this method does not make a network request to Braze servers.

Link copied to clipboard
internal fun requestGeofenceRefresh(location: IBrazeLocation?)

Requests the geofence manager to request a geofence refresh from Braze with geofences appropriate for the reported location.

internal fun requestGeofenceRefresh(ignoreRateLimit: Boolean)

Requests the geofence manager to request a geofence refresh from Braze, ignoring the rate limit if appropriate. The geofence manager will automatically request a location fix for the geofence refresh.

Link copied to clipboard
open override fun requestGeofences(latitude: Double, longitude: Double)

Requests a refresh of Braze Geofences for the specified GPS coordinate.

Link copied to clipboard

Initializes Geofences on the device.

Link copied to clipboard
open override fun requestImmediateDataFlush()

Requests an immediate flush of any analytics data waiting to be sent to Braze's servers.

Link copied to clipboard
open override fun requestLocationInitialization()

Clients apps may call this method when location permissions are granted to request immediate initialization of geofences as appropriate. This will also request a single location update since location permissions were likely not present at the start of the user's session.

Link copied to clipboard

Requests a location fix for the session on the device. This is equivalent to ILocationManager.requestSingleLocationUpdate and should only be called if location permissions have changed on the device.

Link copied to clipboard

Passes an In-App Message back to the TriggerManager.retryTriggeredAction for retrying the fallback actions.

Link copied to clipboard
internal fun run(errorLog: () -> String, earlyReturnIfDisabled: Boolean = true, earlyReturnIfDelayedInitEnabled: Boolean = true, earlyReturnIfUdmUninitialized: Boolean = true, block: () -> Unit)

Used when invoking a block of serially blocked code and neither blocking nor returning a value to, the caller thread.

Link copied to clipboard
internal fun <T> runForResult(defaultValueOnException: T, errorLog: () -> String, earlyReturnIfDisabled: Boolean = true, earlyReturnIfDelayedInitEnabled: Boolean = true, earlyReturnIfUdmUninitialized: Boolean = true, block: suspend CoroutineScope.() -> T): T

Used when invoking a block of serially blocked code and returning some result back to the caller thread.

Safely calls DelayedInitializationProvider.flushPushAnalyticsQueue.

Link copied to clipboard
internal fun schedulePushDelivery(timeInMs: Long)

Logs a push delivery event.

Link copied to clipboard
open override fun setGoogleAdvertisingId(googleAdvertisingId: String?, isLimitAdTrackingEnabled: Boolean)

Sets the Google Advertising ID and associated ad-tracking enabled field for this device. Note that the SDK does not automatically collect this data.

Link copied to clipboard
open override fun setSdkAuthenticationSignature(signature: String)

Sets the signature used for SDK authentication for the currently identified user.

Link copied to clipboard
private fun setSyncPolicyOfflineStatus(isOffline: Boolean)

Sets the BrazeManager and sync policy to match the isOffline value. When offline, network requests will not be added to the dispatch queue and the sync policy will be stopped.

private fun setUserSpecificMemberVariablesAndStartDispatch(dependencyProvider: UserDependencyManager)
Link copied to clipboard
open override fun subscribeToBannersErrors(subscriber: IEventSubscriber<BannersRequestFailureEvent>)

Subscribes to Banners error events. The subscriber callback will be called when Banners fail to update. The subscriber will be called with a BannersRequestFailureEvent.

Link copied to clipboard

Subscribes to Banners update events. The subscriber callback will be called when Banners are updated. The subscriber will be called with a BannersUpdatedEvent.

Link copied to clipboard

Subscribes to user change events. The subscriber callback will be called when a user is changed via IBraze.changeUser. The subscriber will be called with a BrazeUserChangeEvent. Events may be fired for the same user multiple times, even if no transition has occurred.

Link copied to clipboard

Subscribes to Content Cards events. The subscriber callback will be called when Content Cards is updated. The subscriber will be called with a ContentCardsUpdatedEvent.

Link copied to clipboard

Subscribes to Feature Flags events. The subscriber callback will be called when Feature Flags are updated. The subscriber will be called with a FeatureFlagsUpdatedEvent.

Link copied to clipboard

Subscribes to network failures that have occurred within the SDK.

Link copied to clipboard

Subscribes to in-app message events. The subscriber callback will be called when a new in-app message is sent. The subscriber will be called with a InAppMessageEvent.

Link copied to clipboard

Subscribes to "no matching trigger" events. The subscriber callback will be called when a open, custom event, or purchase event is sent, but there's not a corresponding in-app message that was triggered by it. The subscriber will be called with a NoMatchingTriggerEvent.

Link copied to clipboard

Subscribes to push notifications handled by the Braze SDK.

Link copied to clipboard

Subscribes to SDK Authentication failures.

Link copied to clipboard

Subscribes to Session start and close events. The subscriber callback will be called when a session is created or sealed. The subscriber will be called with a SessionStateChangedEvent.

Link copied to clipboard
internal fun validateAndStorePushId(pushId: String): Boolean

Validates the push identifier and if unique, stores it.

Link copied to clipboard
private fun verifyProperSdkSetup()

Verifies that the Braze SDK is properly integrated according to https://www.braze.com/docs/developer_guide/platform_integration_guides/android/initial_sdk_setup/android_sdk_integration/

Link copied to clipboard
@VisibleForTesting(otherwise = 5)
internal fun waitForUserDependencyThread()

Waits until any queued tasks in the mUserDependencyExecutor are finished. This is NOT intended to be used outside of tests.