Android performance integration guide

Step-by-step instructions for adding performance monitoring to your Android projects.

The BugSnag Performance Android integration automatically instruments app starts, activity and fragment loads and okhttp network requests. Arbitrary operations can also be manually instrumented in your code.

New to BugSnag? Create an account

Looking for error monitoring? See our integration guide

Installation

Add the following dependencies to your Module Gradle Settings, usually found at <project_dir>/app/build.gradle:

dependencies {
    // ...
    implementation "com.bugsnag:bugsnag-android-performance:X.Y.Z"
}

The latest available version of bugsnag-android-performance is v1.2.2.

Basic configuration

Configure your API key in the <application> tag of your App Manifest file (usually in src/main/AndroidManifest.xml):

<application ...>
  <meta-data android:name="com.bugsnag.android.API_KEY"
             android:value="your-api-key-here"/>
</application>

This is the same API key and the same metadata key used by the BugSnag Error Monitoring library.

You can find your API key in Project Settings from your BugSnag dashboard.

Application

Initialize BugSnag Performance in the onCreate callback of your Application subclass:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        BugsnagPerformance.start(this);
    }
}
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        BugsnagPerformance.start(this)
    }
}

Instrumenting app starts

BugSnag will automatically detect and report app starts, measuring them until the first participating “Screen load” span has ended (see below for details). These timings are shown under the “App starts” tab in the BugSnag Performance dashboard.

We recommend you enhance your app start measurement by manually reporting when the Application class is initialized:

public class MyApp extends Application {
    static {
        BugsnagPerformance.reportApplicationClassLoaded();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        BugsnagPerformance.start(PerformanceConfiguration.load(this));
    }
}
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        BugsnagPerformance.start(PerformanceConfiguration.load(this))
    }

    companion object {
        init {
            BugsnagPerformance.reportApplicationClassLoaded()
        }
    }
}

The instrumentation determines whether the app is being launched for the first time since installation or reboot and so is a full “cold” start, or whether this is a “warm” start where the Application is already loaded, or a “hot” start where the previous launch is simply being resumed. These three app start types are displayed separately on your BugSnag dashboard.

If you have Activities or Fragments that you wish to consider part of your app start period, use the doNotEndAppStart configuration option or @DoNotEndAppStart annotation. You can also disable the automatic instrumentation of app starts, using autoInstrumentAppStarts configuration option.

Instrumenting Activity and Fragment loads

Automatic instrumentation

BugSnag will automatically detect and report Activity loads, measuring the time taken between the start of onCreate and the end of onResume. These timings are shown under the “Screen loads” tab in the BugSnag Performance dashboard.

If you use Fragments in your app, you can also add the bugsnag-android-performance-appcompat module to your project to automatically detect parts of the Fragment lifecycle:

dependencies {
    implementation "com.bugsnag:bugsnag-android-performance:X.Y.Z"
    implementation "com.bugsnag:bugsnag-android-performance-appcompat:X.Y.Z"
}

If you are using ProGuard, DexGuard or R8, in order to see the full name of the Fragments that we instrument, you’ll need to tell ProGuard explicitly to not strip this information by adding the following rule to your ProGuard configuration:

-keep class * extends androidx.fragment.app.Fragment

To prevent certain Activities and Fragments from being instrumented, use the doNotAutoInstrument configuration option or @DoNotAutoInstrument annotation. Alternatively, to disable automatic instrumentation of activities entirely, or to control the point at when an activity should be defined as loaded, see the autoInstrumentActivities configuration option.

Manual instrumentation

To instrument view loads manually, use startViewLoadSpan and endViewLoadSpan passing the Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BugsnagPerformance.startViewLoadSpan(this);
}

public void onResume() {
    super.onResume();
    BugsnagPerformance.endViewLoadSpan(this);
}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    BugsnagPerformance.startViewLoadSpan(this)
}

override fun onResume() {
    super.onResume()
    BugsnagPerformance.endViewLoadSpan(this)
}

Alternatively, the span can be created by passing individual attributes for the type and name. You should ensure the span is ended by holding a reference to the returned span and calling end in an appropriate event handler:

// at the start of a view loading:
Span viewSpan = BugsnagPerformance.startViewLoadSpan(
    ViewType.ACTIVITY,
    "MyActivity"
);
// in an "onResume" or similar:
viewSpan.end();
// at the start of a view loading:
val viewSpan = BugsnagPerformance.startViewLoadSpan(
    ViewType.ACTIVITY,
    "MyActivity"
)
// in an "onResume" or similar:
viewSpan.end()

You can use startViewLoadSpan in this way to manually instrument Jetpack Compose views.

Instrumenting network requests

Automatic instrumentation

BugSnag can automatically detect and report network requests from OkHttp using the bugsnag-android-performance-okhttp module. These timings are shown under the “Network requests” tab in the BugSnag Performance dashboard.

To start capturing network requests, add bugsnag-android-performance-okhttp as a dependency to your project:

dependencies {
    implementation "com.bugsnag:bugsnag-android-performance:X.Y.Z"
    implementation "com.bugsnag:bugsnag-android-performance-okhttp:X.Y.Z"
    implementation "com.squareup.okhttp3:okhttp:4.+"
}

BugSnag supports OkHttp versions 3, 4 and 5.

Then configure the BugSnag OkHttp EventListener on your OkHttpClient:

OkHttpClient client = new OkHttpClient.Builder()
    .eventListener(new BugsnagPerformanceOkhttp())
    .build();
val client = OkHttpClient.Builder()
    .eventListener(BugsnagPerformanceOkhttp())
    .build()

The networkRequestCallback configuration option allows you to control the data sent in these network request spans using a callback.

Manual instrumentation

To instrument network requests manually use startNetworkRequestSpan:

URL url = new URL("https://bugsnag.com");
try (Span span = BugsnagPerformance.startNetworkRequestSpan(url, "GET")) {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    NetworkRequestAttributes.setResponseCode(span, connection.getResponseCode());
    NetworkRequestAttributes.setResponseContentLength(span, connection.getContentLengthLong());

    // consume the connection as normal
}
val url = URL("https://bugsnag.com")
BugsnagPerformance.startNetworkRequestSpan(url, "GET").use { span ->
    val connection = url.openConnection() as HttpURLConnection
    NetworkRequestAttributes.setResponseCode(span, connection.responseCode)
    NetworkRequestAttributes.setResponseContentLength(span, connection.contentLengthLong)

    // consume the connection as normal
}

Sending custom spans

To send custom spans to BugSnag for any other operations you wish to measure, use BugsnagPerformance.startSpan to start a span, and call the span’s end method to end the measurement:

try (BugsnagPerformance.startSpan("Login")) {
    LoginApi.login();
}
BugsnagPerformance.startSpan("Login").use {
    LoginApi.login()
}

Span is Closable and can be used either in a try-with-resources (in Java), or with the use function (in Kotlin)

A Span can also be manually ended using its end function if the measured process cannot be encapsulated in a single block:

Span span = BugsnagPerformance.startSpan("Login");
LoginApi.login(() -> {
    // login is complete
    span.end();
});
val span = BugsnagPerformance.startSpan("Login")
LoginApi.login {
    // login is complete
    span.end()
}

The options parameter allows you to customize some elements of the span’s behavior:

Reporting child-only spans

If a custom span is “first class”, its performance characteristics will be aggregated and shown in the “Custom” tab of the BugSnag dashboard. If the custom span is useful only for adding insight into the performance of its parent (through the waterfall diagram on the span instance page), you should set the isFirstClass span option to false:

BugsnagPerformance.startSpan("always-nested", SpanOptions.DEFAULTS.setFirstClass(false));
BugsnagPerformance.startSpan("always-nested", SpanOptions.DEFAULTS.setFirstClass(false))

Controlling span hierarchies

When viewing a single instance of a span in the BugSnag dashboard, a waterfall diagram will show you that instance’s children and their children, and so on. This allows you to see in more detail where the time was spent, and aid diagnosing and fixing any problems. When creating your own spans, you can use the options parameter to control their parent-child relationships to produce a meaningfully representative hierarchy in your dashboard. See Maintaining span context for more information.

Start time override

By default, a span will use the current timestamp as its start time. However, you can use the startTime span option to report spans that have already started by providing your own timestamp. You can also end a span with your own timestamp to provide a retrospective end time:

long activityStartTime = System.currentTimeMillis();
// Do some work
long activityEndTime = System.currentTimeMillis();

BugsnagPerformance.startSpan("retro-span", SpanOptions.DEFAULTS.startTime(activityStartTime))
    .end(activityEndTime);
var activityStartTime = System.currentTimeMillis()
// Do some work
var activityEndTime = System.currentTimeMillis()

BugsnagPerformance.startSpan("retro-span", SpanOptions.DEFAULTS.startTime(activityStartTime))
    .end(activityEndTime)