Overview

If you have not set up the SDK yet, follow the in-app setup instructions or refer to the Android RUM setup documentation.

Enrich user sessions

Android RUM automatically tracks attributes such as user activity, screens, errors, and network requests. See the RUM Data Collection documentation to learn about the RUM events and default attributes. You can further enrich user session information and gain finer control over the attributes collected by tracking custom events.

Custom Views

In addition to tracking views automatically, you can also track specific distinct views (such as activities and fragments) when they become visible and interactive in the onResume() lifecycle. Stop tracking when the view is no longer visible. Most often, this method should be called in the frontmost Activity or Fragment:

    fun onResume() {
      GlobalRumMonitor.get().startView(viewKey, viewName, viewAttributes)
    }

    fun onPause() {
      GlobalRumMonitor.get().stopView(viewKey, viewAttributes)
    }
    public void onResume() {
         GlobalRumMonitor.get().startView(viewKey, viewName, viewAttributes);
    }
    
    public void onPause() {
         GlobalRumMonitor.get().stopView(viewKey, viewAttributes);
    }

Notify the SDK that your view finished loading

iOS RUM tracks the time it takes for your view to load. To notify the SDK that your view has finished loading, call the addViewLoadingTime(override=) method through the GlobalRumMonitor instance. Call this method when your view is fully loaded and displayed to the user:

    @OptIn(ExperimentalRumApi::class)
    fun onViewLoaded() {
         GlobalRumMonitor.get().addViewLoadingTime(override = false)
    }
    @OptIn(markerClass = ExperimentalRumApi.class)
    public void onViewLoaded() {
         GlobalRumMonitor.get().addViewLoadingTime(override);
    }

Use the override option to replace the previously calculated loading time for the current view.

After the loading time is sent, it is accessible as @view.loading_time and is visible in the RUM UI. Please note that this API is still experimental and might change in the future.

Add your own performance timing

In addition to RUM’s default attributes, you can measure where your application is spending its time by using the addTiming API. The timing measure is relative to the start of the current RUM view. For example, you can time how long it takes for your hero image to appear:

   fun onHeroImageLoaded() {
         GlobalRumMonitor.get().addTiming("hero_image")
   } 
    public void onHeroImageLoaded() {
         GlobalRumMonitor.get().addTiming("hero_image");
    }

Once the timing is sent, the timing is accessible as @view.custom_timings.<timing_name>. For example: @view.custom_timings.hero_image. You must create a measure before graphing it in RUM analytics or in dashboards.

Custom Actions

In addition to tracking actions automatically, you can also track specific custom user actions (such as taps, clicks, and scrolls) with RumMonitor#addAction. For continuous action tracking (for example, tracking a user scrolling a list), use RumMonitor#startAction and RumMonitor#stopAction.

Note the action type should be one of the following: “custom”, “click”, “tap”, “scroll”, “swipe”, “back”.

    fun onUserInteraction() { 
         GlobalRumMonitor.get().addAction(actionType, name, actionAttributes)
    }
    public void onUserInteraction() {
         GlobalRumMonitor.get().addAction(actionType, name, actionAttributes);
    }

Enrich resources

When tracking resources automatically, provide a custom RumResourceAttributesProvider instance to add custom attributes to each tracked network request. For example, if you want to track a network request’s headers, create an implementation as follows, and pass it in the constructor of the DatadogInterceptor.

class CustomRumResourceAttributesProvider : RumResourceAttributesProvider {
    override fun onProvideAttributes(
        request: Request,
        response: Response?,
        throwable: Throwable?
    ): Map<String, Any?> {
        val headers = request.headers
        return headers.names().associate {
            "headers.${it.lowercase(Locale.US)}" to headers.values(it).first()
        }
    }
}
public class CustomRumResourceAttributesProvider implements RumResourceAttributesProvider {
    @NonNull
    @Override
    public Map<String, Object> onProvideAttributes(
            @NonNull Request request,
            @Nullable Response response,
            @Nullable Throwable throwable
    ) {
        Map<String, Object> result = new HashMap<>();
        Headers headers = request.headers();

        for (String key : headers.names()) {
            String attrName = "headers." + key.toLowerCase(Locale.US);
            result.put(attrName, headers.values(key).get(0));
        }
        
        return result;
    }
}

Custom Resources

In addition to tracking resources automatically, you can also track specific custom resources (such as network requests and third-party provider APIs) with methods (such as GET and POST) while loading the resource with RumMonitor#startResource. Stop tracking with RumMonitor#stopResource when it is fully loaded, or RumMonitor#stopResourceWithError if an error occurs while loading the resource.

    fun loadResource() {
         GlobalRumMonitor.get().startResource(resourceKey, method, url, resourceAttributes)
         try {
           // do load the resource
           GlobalRumMonitor.get().stopResource(resourceKey, resourceKind, additionalAttributes)
         } catch (e: Exception) {
           GlobalRumMonitor.get().stopResourceWithError(resourceKey, message, origin, e)
         } 
    }
    public void loadResource() {
         GlobalRumMonitor.get().startResource(resourceKey, method, url, resourceAttributes);
         try {
             // do load the resource
             GlobalRumMonitor.get().stopResource(resourceKey, resourceKind, additionalAttributes);
         } catch (Exception e) {
             GlobalRumMonitor.get().stopResourceWithError(resourceKey, message, origin, e);
         }
    }

Custom Errors

To track specific errors, notify the monitor when an error occurs with the message, source, exception, and additional attributes. Refer to the Error Attributes documentation.

   GlobalRumMonitor.get().addError(message, source, throwable, attributes)

Add user properties

You can use the addUserProperties API to append extra user properties to previously set properties.

fun addUserProperties(extraInfo: Map<String, Any?>, sdkCore: SdkCore = getInstance()) {
    sdkCore.addUserProperties(extraInfo)
}

Event and data management

The Android SDK first stores events and only uploads events when the intake specifications conditions are met.

Clear all data

You have the option of deleting all unsent data stored by the SDK with the clearAllData API.

fun clearAllData(sdkCore: SdkCore = getInstance()) {
    sdkCore.clearAllData()
}

Stop data collection

You can use the StopInstance API to stop the SDK instance assigned to the given name (or the default instance if the name is null) from collecting and uploading data further.

   fun stopInstance(instanceName: String? = null) {
       synchronized(registry) {
           val instance = registry.unregister(instanceName)
           (instance as? DatadogCore)?.stop()
       }
   }

Control event buildup

Many operations, such as data processing and event input/output, are queued in background threads to handle edge cases where the queue has grown so much that there could be delayed processing, high memory usage, or Application Not Responding (ANR) errors.

You can control the buildup of events on the SDK with the setBackpressureStrategy API. This API ignores new tasks if a queue reaches 1024 items.

   fun setBackpressureStrategy(backpressureStrategy: BackPressureStrategy): Builder {
       coreConfig = coreConfig.copy(backpressureStrategy = backpressureStrategy)
       return this
   }

See an example of this API being used.

Set remote log threshold

You can define the minimum log level (priority) to send events to Datadog in a logger instance. If the log priority is below the one you set at this threshold, it does not get sent. The default value is -1 (allow all).

   fun setRemoteLogThreshold(minLogThreshold: Int): Builder {
       minDatadogLogsPriority = minLogThreshold
       return this
   }

Track custom global attributes

In addition to the default RUM attributes captured by the RUM Android SDK automatically, you can choose to add additional contextual information, such as custom attributes, to your RUM events to enrich your observability within Datadog. Custom attributes allow you to filter and group information about observed user behavior (such as cart value, merchant tier, or ad campaign) with code-level information (such as backend services, session timeline, error logs, and network health).

Track User Sessions

Adding user information to your RUM sessions makes it easy to:

  • Follow the journey of a given user
  • Know which users are the most impacted by errors
  • Monitor performance for your most important users
User API in RUM UI

The following attributes are optional, you should provide at least one of them:

AttributeTypeDescription
usr.idStringUnique user identifier.
usr.nameStringUser friendly name, displayed by default in the RUM UI.
usr.emailStringUser email, displayed in the RUM UI if the user name is not present. It is also used to fetch Gravatars.

To identify user sessions, use the setUserInfo API, for example:

Datadog.setUserInfo('1234', 'John Doe', 'john@doe.com')

Track attributes

    // Adds an attribute to all future RUM events
    GlobalRumMonitor.get().addAttribute(key, value)

    // Removes an attribute to all future RUM events
    GlobalRumMonitor.get().removeAttribute(key)

Track widgets

Widgets are not automatically tracked with the SDK. To send UI interactions from your widgets manually, call the Datadog API. See example.

Initialization parameters

You can use the following methods in Configuration.Builder when creating the Datadog configuration to initialize the library:

setFirstPartyHosts()
Defines hosts that have tracing enabled and have RUM resources categorized as first-party. Note: If you define custom tracing header types in the Datadog configuration and are using a tracer registered with GlobalTracer, make sure the same tracing header types are set for the tracer in use.
useSite(DatadogSite)
Switches target data to EU1, US1, US3, US5, US1_FED and AP1 sites.
setFirstPartyHostsWithHeaderType
Sets the list of first party hosts and specifies the type of HTTP headers used for distributed tracing.
setBatchSize([SMALL|MEDIUM|LARGE])
Defines the individual batch size for requests sent to Datadog.
setUploadFrequency([FREQUENT|AVERAGE|RARE])
Defines the frequency for requests made to Datadog endpoints (if requests are available).
setBatchProcessingLevel(LOW|MEDIUM|HIGH)
Defines the number of batches sent in each upload cycle.
setAdditionalConfiguration
Allows you to provide additional configuration values that can be used by the SDK.
setProxy
Enables a custom proxy for uploading tracked data to Datadog’s intake.
setEncryption(Encryption)
Set an encryption function applied to data stored locally on the device.
setPersistenceStrategyFactory
Allows you to use a custom persistence strategy.
setCrashReportsEnabled(Boolean)
Allows you to control whether JVM crashes are tracked or not. The default value is true.
setBackpressureStrategy(BackPressureStrategy)
Define the strategy the SDK uses when handling large volumes of data and internal queues are full.

You can use the following methods in RumConfiguration.Builder when creating the RUM configuration to enable RUM features:

trackUserInteractions(Array<ViewAttributesProvider>)
Enables tracking user interactions (such as tap, scroll, or swipe). The parameter also allows you to add custom attributes to the RUM Action events based on the widget with which the user interacted.
disableUserInteractionTracking
Disables the user interaction automatic tracker.
useViewTrackingStrategy(strategy)
Defines the strategy used to track views. See Automatically track views for more information.
trackLongTasks(durationThreshold)
Enables tracking tasks taking longer than durationThreshold on the main thread as long tasks in Datadog. See Automatically track long tasks for more information.
trackNonFatalAnrs(Boolean)
Enables tracking non-fatal ANRs. This is enabled by default on Android API 29 and below, and disabled by default on Android API 30 and above.
setVitalsUpdateFrequency([FREQUENT|AVERAGE|RARE|NEVER])
Sets the preferred frequency for collecting mobile vitals.
setSessionSampleRate(<sampleRate>)
Sets the RUM sessions sample rate. (A value of 0 means no RUM events are sent. A value of 100 means all sessions are kept.)
setSessionListener(RumSessionListener)
Sets a listener to be notified on when a new RUM Session starts.
setTelemetrySampleRate
The sampling rate for the SDK internal telemetry utilized by Datadog. This must be a value between 0 and 100. By default, this is set to 20.
setViewEventMapper
Sets the ViewEventMapper for the RUM ViewEvent. You can use this interface implementation to modify the ViewEvent attributes before serialization.
setResourceEventMapper
Sets the EventMapper for the RUM ResourceEvent. You can use this interface implementation to modify the ResourceEvent attributes before serialization.
setActionEventMapper
Sets the EventMapper for the RUM ActionEvent. You can use this interface implementation to modify the ActionEvent attributes before serialization.
setErrorEventMapper
Sets the EventMapper for the RUM ErrorEvent. you can use this interface implementation to modify the ErrorEvent attributes before serialization.
setLongTaskEventMapper
Sets the EventMapper for the RUM LongTaskEvent. You can use this interface implementation to modify the LongTaskEvent attributes before serialization.
trackBackgroundEvents
Enable/disable tracking RUM events when no activity is happening in the foreground. By default, background events are not tracked. Enabling this feature might increase the number of sessions tracked, and therefore your billing.
trackFrustrations
Enable/disable tracking of frustration signals.
useCustomEndpoint
Use RUM to target a custom server.

Automatically track views

To automatically track your views (such as activities and fragments), provide a tracking strategy at initialization. Depending on your application’s architecture, you can choose one of the following strategies:

ActivityViewTrackingStrategy
Every activity in your application is considered a distinct view.
FragmentViewTrackingStrategy
Every fragment in your application is considered a distinct view.
MixedViewTrackingStrategy
Every activity or fragment in your application is considered a distinct view.
NavigationViewTrackingStrategy
Recommended for Android Jetpack Navigation library users. Each Navigation destination is considered a distinct view.

For instance, to set each fragment as a distinct view, use the following configuration in your setup:

    val rumConfig = RumConfiguration.Builder(applicationId)
     .useViewTrackingStrategy(FragmentViewTrackingStrategy(...))
     .build()
    RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
     .useViewTrackingStrategy(new FragmentViewTrackingStrategy(...))
     .build();

For ActivityViewTrackingStrategy, FragmentViewTrackingStrategy, or MixedViewTrackingStrategy, you can filter which Fragment or Activity is tracked as a RUM View by providing a ComponentPredicate implementation in the constructor:

    val rumConfig = RumConfiguration.Builder(applicationId)
     .useViewTrackingStrategy(
     ActivityViewTrackingStrategy(
         trackExtras = true,
         componentPredicate = object : ComponentPredicate<Activity> {
             override fun accept(component: Activity): Boolean {
                 return true
             }

             override fun getViewName(component: Activity): String? = null
         })
     )
     .build()  
     RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
         .useViewTrackingStrategy(new ActivityViewTrackingStrategy(
             true,
             new ComponentPredicate<Activity>() {
                 @Override
                 public boolean accept(Activity component) {
                     return true;
                 }

                 @Override
                 public String getViewName(Activity component) {
                     return null;
                 }
             }
         ))
         .build();

Note: By default, the library is using ActivityViewTrackingStrategy. If you decide not to provide a view tracking strategy, you must manually send the views by calling the startView and stopView methods yourself.

Automatically track network requests

To get timing information in resources (such as third-party providers, network requests) such as time to first byte or DNS resolution, customize the OkHttpClient to add the EventListener factory:

  1. Add the Gradle dependency to the dd-sdk-android-okhttp library in the module-level build.gradle file:

    dependencies {
        implementation "com.datadoghq:dd-sdk-android-okhttp:x.x.x"
    }
    
  2. Add add the EventListener factory:

    val okHttpClient = OkHttpClient.Builder()
     .addInterceptor(DatadogInterceptor())
     .eventListenerFactory(DatadogEventListener.Factory())
     .build()
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
     .addInterceptor(new DatadogInterceptor())
     .eventListenerFactory(new DatadogEventListener.Factory())
     .build();

Automatically track long tasks

Long running operations performed on the main thread can impact the visual performance and reactivity of your application. To track these operations, define the duration threshold above which a task is considered too long.

    val rumConfig = RumConfiguration.Builder(applicationId)
     // …
     .trackLongTasks(durationThreshold)
     .build()

For example, to replace the default 100 ms duration, set a custom threshold in your configuration.

   val rumConfig = RumConfiguration.Builder(applicationId)
     // …
     .trackLongTasks(250L) // track tasks longer than 250ms as long tasks
     .build()
    RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
      // …
      .trackLongTasks(durationThreshold)
      .build();

For example, to replace the default 100 ms duration, set a custom threshold in your configuration.

   RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
     // …
     .trackLongTasks(250L) // track tasks longer than 250ms as long tasks
     .build();

Modify or drop RUM events

To modify some attributes in your RUM events, or to drop some of the events entirely before batching, provide an implementation of EventMapper<T> when initializing the RUM Android SDK:

    val rumConfig = RumConfiguration.Builder(applicationId)
     // ...
     .setErrorEventMapper(rumErrorEventMapper)
     .setActionEventMapper(rumActionEventMapper)
     .setResourceEventMapper(rumResourceEventMapper)
     .setViewEventMapper(rumViewEventMapper)
     .setLongTaskEventMapper(rumLongTaskEventMapper)
     .build()
    RumConfiguration rumConfig = new RumConfiguration.Builder(applicationId)
      // ...
      .setErrorEventMapper(rumErrorEventMapper)
      .setActionEventMapper(rumActionEventMapper)
      .setResourceEventMapper(rumResourceEventMapper)
      .setViewEventMapper(rumViewEventMapper)
      .setLongTaskEventMapper(rumLongTaskEventMapper)
      .build();

When implementing the EventMapper<T> interface, only some attributes are modifiable for each event type:

Event typeAttribute keyDescription
ViewEventview.referrerURL that linked to the initial view of the page.
view.urlURL of the view.
view.nameName of the view.
ActionEvent
action.target.nameTarget name.
view.referrerURL that linked to the initial view of the page.
view.urlURL of the view.
view.nameName of the view.
ErrorEvent
error.messageError message.
error.stackStacktrace of the error.
error.resource.urlURL of the resource.
view.referrerURL that linked to the initial view of the page.
view.urlURL of the view.
view.nameName of the view.
ResourceEvent
resource.urlURL of the resource.
view.referrerURL that linked to the initial view of the page.
view.urlURL of the view.
view.nameName of the view.
LongTaskEvent
view.referrerURL that linked to the initial view of the page.
view.urlURL of the view.
view.nameName of the view.

Note: If you return null from the EventMapper<T> implementation, the event is dropped.

Retrieve the RUM session ID

Retrieving the RUM session ID can be helpful for troubleshooting. For example, you can attach the session ID to support requests, emails, or bug reports so that your support team can later find the user session in Datadog.

You can access the RUM session ID at runtime without waiting for the sessionStarted event:

GlobalRumMonitor.get().getCurrentSessionId { sessionId ->
  currentSessionId = sessionId
}

Further Reading

Additional helpful documentation, links, and articles:

PREVIEWING: mervebolat/span-id-preprocessing