Android SDK Reference

This is a reference guide for all Android SDK requirements, known limitations, API reference, and performance impact information.

All Android SDK artifacts are distributed through Maven Central.

For notes on the latest SDK versions, see our Android changelog.

❗️

If you're using Heap's Classic Android SDK and thinking about switching to our newest offerings, please note that some event definitions might need to be repaired after upgrade. Be sure to check out the full breakdown of the differences between our SDKs here.

Need help with this process? Please post in Community or contact us via the Get support page in Heap.

📘

This reference is exclusive to Heap's current Android SDK offerings. For information about Heap's Classic Android SDK, you can visit its documentation here.

Heap Android Core Reference

Requirements + Known Limitations

  • This SDK requires Android API level 16 or higher.

Required Permissions

The Heap Android Core SDK will attempt to add all required permissions to your manifest. In the event that you receive any permission errors, add the following permissions to your application's AndroidManifest.xml file.

<!-- Needed for basic functionality -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- If targeting Android 13+ and requesting advertiser ID capture. -->
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>

Installation

The Heap Android Core SDK can be installed as a Gradle dependency. All of our SDKs are distributed through Maven Central.

dependencies {  
  implementation 'io.heap.core:heap-android-core:0.7.+'  
}
dependencies {  
  implementation("io.heap.core:heap-android-core:0.7.+")
}

API Reference

Heap

  • Type: Kotlin object / Java class
  • Import: io.heap.core.Heap

The public-facing API for the Heap Android Core SDK.

Note: All methods are static.

fun startRecording(context: Context, envId: String, options: Options = Options())

Description
Initializes the Heap SDK and enables Heap to start recording data.

Parameters

  • context: The non-null application Context used to initialize Heap SDK components.
  • envId: The non-null string environment ID to which data should be attributed.
  • options (optional): The non-null Options object with installation-specific configuration options. Default values defined by Options constructor.

Return Value

None.

fun stopRecording()

Description

Shuts down the Heap SDK and prevents any further data collection.

Parameters

None.

Return Value

None.

fun track(event: String, properties: Map<String, Any> = mapOf(), timestamp: Date = Date(), sourceInfo: SourceInfo? = null, pageview = Pageview? = null)

Description

Creates an event message to be tracked and sent to the Heap API.

Parameters

  • event: The string name of the event.
  • properties (optional): The non-null Map of properties to associate with the event. Map keys should be represented by strings and values can be any combination of any Number, Boolean, String, or Java/Kotlin object that implements HeapProperty. Defaults to an empty map.
  • timestamp (optional): The non-null Date of when the event occurs. Defaults to the current time.
  • sourceInfo (optional): The nullable SourceInfo object if this event was generated by an autocapture SDK. Defaults to null. Customer implementations should not assign values for this parameter.
  • pageview (optional): The Pageview to associate with the tracked event. This is most commonly the case if the event was generated by an autocapture SDK. Defaults to null. Customer implementations should not assign values for this parameter.

Return Value

None.

fun identify(identity: String)

Description

Assigns an identity to be associated with all future events.

Parameters

  • identity: The non-null string value representing the identity to associate with future events.

Return Value

None.

fun resetIdentity()

Description

Unsets any assigned identity. No identity will be associated with future events until identify is called again.

Parameters

None.

Return Value

None.

fun addUserProperties(properties: Map<String, Any>)

Description

Add a collection of properties to be associated with the current user.

Parameters

  • properties: The non-null Map of properties to associate with the current user. Map keys should be represented by strings and values can be any combination of any Number, Boolean, String, or Java/Kotlin object that implements HeapProperty.

Return Value

None.

fun addEventProperties(properties: Map<String, Any>)

Description

Add a collection of properties to be associated with all future events.

Parameters

  • properties: The non-null Map of properties to associate with future events. Map keys should be represented by strings and values can be any combination of any Number, Boolean, String, or Java/Kotlin object that implements HeapProperty.

Return Value

None.

fun removeEventProperty(name: String)

Description

Removes a single property from the collection of event-wide properties.

Parameters

  • name: The non-null name of the property to remove. This should correspond to the string key from the map of previously added properties.

Return Value

None.

fun clearEventProperties()

Description

Removes all event-wide properties that were previously added with addEventProperties.

Parameters

None.

Return Value

None.

fun getUserId(): String?

Description

Attempts to retrieve the current user ID if Heap is recording.

Parameters

None.

Return Value

The current user ID or null if not recording.

fun getIdentity(): String?

Description

Attempts to retrieve the current identity if one has been set.

Parameters

None.

Return Value

The current identity or null if no identity has been set with identify.

fun getSessionId(): String?

Description

Attempts to retrieve the current session ID if there is an active session.

Parameters

None.

Return Value

The current session ID or null if there is no active session.

fun fetchSessionId(): String?

Description

Attempts to retrieve the current session ID if a session has been started. If there is no active session and recording has started, a new session will be created before returning the ID.

Parameters

None.

Return Value

The current session ID or the ID of a newly created session if there is no active session.

fun setLogLevel(logLevel: LogLevel)

Description

Sets the current LogLevel for Heap SDK logs. By default, the Heap SDK will print messages at the LogLevel.INFO level. This includes any messages that might be helpful in a production environment as well as any critical errors or warnings from the LogLevel.ERROR and LogLevel.WARN log levels. For other log levels, see the documentation for the LogLevel class.

Parameters

  • logLevel: The desired non-null LogLevel of messages to be printed.

Return Value

None.

fun setLogChannel(logChannel: LogChannel)

Description

Sets the LogChannel to which the Heap SDK should send log messages. By default, the Heap SDK will print all log messages to Logcat with different output channels used for different types of messages (LogLevel.INFO -> Log.i, LogLevel.DEBUG -> Log.d, etc).

🚧

Be sure to set the appropriate LogLevel using setLogLevel. Log channels will only receive log messages based on the currently set LogLevel.

Parameters

  • logChannel: The desired non-null LogChannel to which log messages should be sent.

Return Value

None.

Options

  • Type: Kotlin/Java class
  • Import: io.heap.core.Options

Object used to pass configuration options into the Heap SDK at runtime.

Options(baseUri: URI = URI("https://c.us.heap-api.com"), uploadInterval: Double = 15.0, captureAdvertiserId: Boolean = false, disableInteractionTextCapture: Boolean = false, startSessionImmediately: Boolean = false, disableInteractionAccessibilityLabelCapture: Boolean = false, captureVendorId: Boolean = false, messageBatchMessageLimit: Int = 100, clearEventPropertiesOnNewUser: Boolean = false)

Description

Constructor for Options data class.

Parameters

  • baseUri (optional): The URI object specifying the base URI for the desired API endpoint. The Heap SDK resolves paths using this base URI and ignores any pre-existing path elements. This parameter primarily exists for testing and proxying purposes, and in the majority of use cases, this parameter should not be set.
  • uploadInterval (optional): The interval at which event batches should be uploaded to the API. Defaults to 15 seconds. For apps with limited connectivity, it may make sense to increase this interval.

🚧

Shorter upload intervals could degrade app performance as the network thread is firing more frequently.

  • captureAdvertiserId (optional): Whether or not the advertiser ID should be included in tracked events if made available by the device. Defaults to false.
    • If set, the application must also include a Heap Advertiser ID Provider, such as io.heap.core.identifier:ad-id-google or io.heap.core.identifier:ad-id-amazon in order to capture advertiser ID. Only one provider may be included in each build configuration.
  • startSessionImmediately (optional): Whether or not to start the session immediately when startRecording is called. Defaults to false.
  • disableInteractionTextCapture(optional): Whether or visible text should be captured as part of autocaptured event data using the Heap Android View Autocapture SDK.
  • disableInteractionAccessibilityLabelCapture(optional): Whether accessibility text data should be captured as part of autocaptured event data using the Heap Android View Autocapture SDK.
  • captureVendorId(optional): Whether or not the vendor ID should be included in tracked events if made available by the device. Defaults to false.
    • If set, the application must also include a Heap Vendor ID Provider such as io.heap.core.identifier:vendor-id-google which captures the Google App Set ID.
  • messageBatchMessageLimit(optional): Sets the number of event messages to include in each payload. This can be used to control bandwidth usage for applications with poor connectivity. Defaults to 100.
  • clearEventPropertiesOnNewUser(optional): Sets whether or not Heap should clear all event properties when changing users. Prior to version 0.5.0, event properties would clear when changing users. Starting in 0.5.0, event properties no longer clear by default, but this option can be used to retain the old behavior. Defaults to false.

HeapProperty

  • Type: Kotlin/Java interface
  • Import: io.heap.core.api.contract.HeapProperty

Interface for providing arbitrary objects as a Heap property value.

This interface is provided for differentiating between the desired property value and the toString value that might be used elsewhere in code. See the example below:

data class Book(  
  val title: String,  
  val author: String,  
  val year: Int  
): HeapProperty {  
  // toString will return information a string containing the title, author, and year.  
  // toHeapPropertyValue on the other hand will only return the title. This class is  
  // now a valid HeapProperty type, and Heap will serialize it to the value returned  
  // by toHeapPropertyValue--i.e. the title.  
  override fun toHeapPropertyValue(): String {  
    return title  
  }  
}
public class Book implements HeapProperty {
  private String title;
  private String author;
  private int year;
  
  // toString will return information a string containing the title, author, and year.
  // toHeapPropertyValue on the other hand will only return the title. This class is
  // now a valid HeapProperty type, and Heap will serialize it to the value returned
  // by toHeapPropertyValue--i.e. the title.
  @Override
  public String toHeapPropertyValue() {
    return title;
  }
}

fun toHeapPropertyValue(): String

Description

Maps an arbitrary object to a string value for inclusion as a Heap property.

Parameters

None.

Return Value

The property value for the given object as a string.

LogLevel

  • Type: Kotlin/Java enum
  • Import: io.heap.core.logs.LogLevel

LogLevel.NONE

Description

Heap will not print any log messages.

LogLevel.ERROR

Description

Heap will only print the most critical log messages, such as when the SDK encounters an error and needs to shut down.

LogLevel.WARN

Description

Heap will print warning messages for recoverable errors, such as when unexpected data types are passed into the SDK or the network is unreachable.

This level also includes ERROR messages.

LogLevel.INFO

Description

Heap will print messages that are useful in a production environment, such as when recording starts/stops, when a batch of events is successfully sent, or when a new session has begun.

This level is recommended for production environments so that developers can see Heap lifecycle messages in their own logging environment.

This level also includes ERROR and WARN messages.

LogLevel.DEBUG

Description

Heap will print messages that the implementing developer may find helpful. Messages may include things such as invalid environment ID value, truncated event names, or attempting to track an event before recording has started.

This level is recommended for implementing developers during the development process to help with debugging normal installation and tracking issues.

This level also includes ERROR, WARN, and INFO messages.

LogLevel.TRACE

Description

Heap will print messages that help the Heap team diagnose SDK issues. Heap support may ask the implementing developers to enable this log level to gain better insight into issues developers may have encountered when implementing the Heap SDK.

Full event details are also printed at this level.

This level is recommended when gathering information to send to Heap support personnel. Heap support may also ask that this level be turned on to help debug installation and tracking issues that require extra investigation.

This level also includes ERROR, WARN, INFO, and DEBUG messages.

LogChannel

  • Type: Kotlin/Java interface
  • Import: io.heap.core.logs.LogChannel

The contractual interface used to route Heap log messages to a specific output location, such as Logcat, Timber, Arbor, or other logging utilities. The default implementation routes all logs through Logcat.

Can be implemented by client apps to redirect Heap logs through a different logging implementation.

fun printLog(logLevel: LogLevel, message: String, source: String?, throwable: Throwable?)

Description

Logs a single message from the Heap SDK.

Parameters

  • logLevel: The non-null LogLevel associated with this message.
  • message: The non-null string message to print.
  • source: A nullable string name of the source library that produced the message.
  • throwable: A nullable Throwable associated with the logged message.

Return Value

None.

Heap Android View Autocapture Reference

Requirements + Known Limitations

  • The Heap Android View Autocapture SDK requires a minimum SDK version of 21 or higher.
  • The Heap Android View Autocapture SDK requires the Heap Android Core SDK in order to work.
  • The Heap Android View Autocapture SDK requires the Heap Android Gradle Plugin (Plugin ID: io.heap.gradle) in order to perform autocapture. The legacy plugin (com.heapanalytics.android:heap-android-gradle) will not work.
  • The Heap Android View Autocapture SDK does not currently support automatically capturing interactions from UI elements built with Jetpack Compose. To capture interactions on UI elements built with Jetpack Compose, please refer to our Manual Event Tracking guide.

Installation

The Heap Android View Autocapture SDK can be installed as a Gradle dependency. All of our SDKs are distributed through Maven Central.

dependencies {  
  implementation 'io.heap.core:heap-android-core:0.7.+'
  implementation 'io.heap.autocapture:heap-autocapture-view:0.7.+'
}
dependencies {  
  implementation("io.heap.core:heap-android-core:0.7.+")
  implementation("io.heap.autocapture:heap-autocapture-view:0.7.+")
}

API Reference

ViewAutocaptureSDK

  • Type: Kotlin object / Java class
  • Import: io.heap.autocapture.ViewAutocaptureSDK

The public-facing API for the Heap Android View Autocapture SDK.

📘

All methods are static.

fun register(isDefault: Boolean = false)

Description
Registers the Heap Android View Autocapture SDK. Once registered, the SDK will autocapture UI interactions and source pageviews.

Parameters

  • isDefault (optional): Whether or not the Heap View Autocapture SDK should be the default source. This setting informs the Heap Android Core SDK to use the Heap Android View Autocapture SDK as a fallback for assigning pageview information to events if those events do not have a currently registered source or if their source fails to return a valid pageview. Defaults to false.

Return Value

None.

fun deregister()

Description

De-registers the Heap Android View Autocapture SDK. Upon de-registration, the SDK will cease to autocapture UI interactions and source pageviews.

Parameters
None.

Return Value
None.

fun ignoreInteractions(view: View?)

Description

Marks a View object as one on which to ignore all user interactions. Any interactions with children of the View object, if it is a ViewGroup, are also ignored.

While this method allows an app to dynamically mark a View to be ignored, it is also possible to mark a View statically by setting its android:tag attribute to "heapIgnoreInteractions" in the appropriate XML layout resource.

Parameters

  • view: The nullable View on which to ignore interactions. If the View is null, this is a no-op.

Return Value

None.

fun redactText(view: View?)

Description

Marks a View object as one on which to redact all text. Any interactions with children of the View object, if it is a ViewGroup, will also have the text redacted.

While this method allows an app to dynamically mark a View to redact text, it is also possible to mark a View statically by setting its android:tag attribute to "heapRedactText" in the appropriate XML layout resource.

Parameters

  • view: The nullable View on which to redact text. If the View is null, this is a no-op.

Return Value

None.

Heap Gradle Plugin Reference

Requirements + Known Limitations

The Heap Gradle Plugin:

  • Supports version 0.1.0 and higher of the Heap Android View Autocapture SDK.
  • Supports version 1.10.5 and higher of the Classic Heap Android Client SDK.
  • Requires version 7.2 or higher of the Android Gradle Plugin.
  • Is fully compatible with Android Gradle Plugin 8.0.
  • Does not currently support Gradle configuration cache.

API Reference

The Heap Gradle Plugin supports optional extension properties to customize instrumentation behavior and certain capture behaviors. These extension properties can be defined in your application module’s build.gradle file by including an ext block in defaultConfig or in any of your applications build types or product flavors. The table below defines the support extension properties.

📘

All property names are case sensitive.

PropertyTypeDefaultDescription
heapAutoInitBooleanfalseBoolean setting to enable initialization configuration at build time.

If this is false, you must initialize Heap programmatically.

If this is true, you must also set heapEnvId to a stringified 53-bit integer.
heapCaptureAdvertiserIdBooleanfalseBoolean setting to enable Advertiser ID capture.
heapCaptureAndroidIdBooleanfalseBoolean setting to enable Android ID capture. This property only works with the Classic SDK.
heapDisableTextCaptureBooleanfalseBoolean setting to disable text capture on views.
heapEnabledBooleantrueBoolean setting to enable build-time instrumentation for autocapture.

If this is set to false, UI interactions will not be autocaptured.
heapEnvIdStringnullThe Environment ID to use for initialization configuration at build time.

This setting only takes effect if heapAutoInit is set to true. It must be set to the 53-bit stringified integer Env ID that you wish to send data to.

Setting heapEnvId to an invalid or empty string when heapAutoInit is set to true will result in Heap failing to initialize at run-time. Likewise, failure to set heapEnvId or setting heapEnvId to null when heapAutoInit is true will result in Heap failing to initialize at run-time.

📘

Changes from Legacy Instrumentor (heap-android-gradle)

  1. heapEnabled defaults to true for the Heap Gradle Plugin. The legacy plugin (heap-android-gradle) defaults to false.
  2. heapCaptureAdvertiserId only takes effect if heapAutoInit is set to true for the Heap View Autocapture SDK. The Classic autocapture SDK would apply the advertiser ID setting without respect to the heapAutoInit setting. (The new core SDK has affordances to enable/disable advertiser ID capture for programmatic initialization.)

Android Performance Impact FAQ

Performance

  • Question: What is the performance impact of Heap on a Mobile app?
    • Answer: Heap adds virtually zero performance overhead. Heap never blocks the UI thread of the application and RAM is only allocated to process events right before they’re persisted or sent to the server.
  • Question: Does Heap do a ton of main thread writes that could impact the responsiveness of the application?
    • Answer: Heap does not perform any data persistence or networking activity on the main thread. All data persistence and networking operations take place on a background thread.
    • Answer: Heap does perform a very small amount of view traversal on the UI thread to fetch event properties from the corresponding UI objects. This operation is very fast, does not utilize findViewById, and only involves simple property access. All data that is gathered on the UI thread is sent to a background thread for processing.

Network

  • Question: Are events stored if there is no internet connection or are they dropped? & how many events get stored?
    • Answer: All event data is stored in a SQLite database in application private storage. While online, this database should never grow to more than a few dozen events. While offline, all events are stored in the database until they’re able to be uploaded to the server. However, all data more than 6 days old will be routinely pruned from the database to prevent the database from growing endlessly.
    • Question: Does this behavior differ between core & autocapture SDKs?
      • Answer: No. Autocapture data is sent to Core for storage.
  • Question: How does Heap's event tracking impact network bandwidth?
    • Answer: Heap sends event data in small batches every 15 seconds while connected to the internet. While offline, network data remains in storage and no uploads are attempted.
    • Question: What about network data consumption?
      • Answer: Events on Android are roughly 0.5KB in size. Even if we estimate that a typical user produces 2,000 events per day, this only amounts to a single megabyte of data consumption.
    • Question: How does Heap mitigate impacting bandwidth?
      • Answer: Heap batches event data to be sent to the server every 15 seconds to prevent constant network access. Heap also only sends a maximum of 100 events at a time, amounting to roughly 100KB of data per upload. Additionally, if any network errors occur, Heap pushes back the upload process for a full minute to wait for network conditions to improve.

Device

  • Question: Is the user battery life impacted because Heap is running?
    • Answer: Heap should not impact battery life in any meaningful way. Events are batched to be sent periodically to prevent constant network access. This upload frequency should closely match the frequency of network activity of regular app usage for connected applications. If the target application doesn’t not routinely access the network, Heap’s upload interval can be increased to reduce network access and mitigate any unnecessary battery usage.

Storage

  • Question: How much memory does the Heap SDK add to app bundles?
    • Answer: Android Core adds about 500KB to app bundles. Android View Autocapture adds about 130KB.
  • Question: Where does Heap store user ID and session ID information?
    • Answer: Heap stores all event data in a SQLite database in private application storage. Some event metadata, such as environment ID, is stored in a file in private application storage.

Build Features

  • Question: What is the expected build-time impact of adding the Heap SDK?
    • Answer: Android Core is a regular Android dependency that doesn’t rely on any build time instrumentation. As such, adding Android Core does not result in a longer build time.
    • Answer: Android View Autocapture adds a small amount of build time overhead to perform code instrumentation. The exact amount of overhead depends on a number of different factors, such as the speed of the machine producing the build and the number of class files in the application. In testing with large open source applications, we noticed build times increasing 15-25% on clean rebuilds of an application without the use of a build cache. However, rebuilds of application with an existing build cache (typical of a developer making some code changes and rebuilding to test those changes) only saw a 1-5 second increase depending on the number of changes made between builds.
  • Question: What effect will build-time obfuscation tools like ProGuard or R8 have on Heap’s ability to capture data?
    • Answer: Android Core does not use any class name mappings and thus would be unaffected by obfuscation tools. Android View Autocapture contains build-time logic for mapping obfuscated class names so that they appear unobfuscated when collected and ingested by Heap. This build-time logic is known to work with ProGuard, DexGuard, and R8, but may also work with other obfuscation tools.