Android Core Installation

Requirements + Known Limitations

  • This SDK requires Android API level 16 or higher.

📘

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

Installation

  1. Verify that your project is set up to retrieve plugins and dependencies from Maven Central. Android Studio will likely have configured your project in this way when you created it. To verify, make sure the dependencyResolutionManagement.repositories block in your project’s settings.gradle file (or settings.gradle.kts file) calls mavenCentral() like so:
dependencyResolutionManagement {
    repositories {
        ...
        mavenCentral()
    }
    ...
}
dependencyResolutionManagement {
    repositories {
        ...
        mavenCentral()
    }
    ...
}
  1. In the dependencies block of your application module’s build.gradle file, add the Heap Android Core SDK as an implementation dependency:
dependencies {
    ...
    implementation 'io.heap.core:heap-android-core:0.3.+'
}
dependencies {
    ...
    implementation("io.heap.core:heap-android-core:0.1.+")
}
  1. Complete the instructions in the Initializing Heap Android Core and Completing Setup sections.
  2. Build your app!

Initializing Heap Android Core

The Heap Android Core SDK is always either recording or not recording. When the SDK isn't recording, the APIs for tracking events, managing users, and setting user and event properties are no-ops. To avail yourself of these APIs, you'll need to do the following:

  1. When you want to start recording, call Heap.startRecording in the manner shown in the code snippet below. We typically recommend invoking this method in Application.onCreate as the snippet does below, but Heap.startRecording can be called anywhere.
import io.heap.core.Heap
...

class MyApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    // Replace YOUR_ENVIRONMENT_ID with the ID of the Heap environment you wish to send data to.
    Heap.startRecording(applicationContext, "YOUR_ENVIRONMENT_ID")
    ...
  }
  ...
}
import io.heap.core.Heap;
...

class MyApplication extends Application {
  @Override
  protected void onCreate() {
    super.onCreate();
    // Replace YOUR_ENVIRONMENT_ID with the ID of the Heap environment you wish to send data to.
    Heap.startRecording(getApplicationContext(), "YOUR_ENVIRONMENT_ID");
    ...
  }
  ...
}

Completing Setup

  1. Ensure that your app has permission to access the internet by adding the internet permission to your application’s AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />

API Methods

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 shouldn't 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 shouldn't 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)

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 most use cases, this parameter shouldn't 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.

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 won't 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.