Android integration guide

Add Bugsnag to your Android apps to automatically capture and report crashes.

The Bugsnag Android integration detects and reports crashes from uncaught Java or Kotlin exceptions, C signal handlers, and C++ exceptions, as well as ANRs. The integration supports Android API level 14+ and NDK revision 12b and above.

New to Bugsnag? Create an account

Installation

Add the following dependency to your Project Gradle Settings, <project_dir>/build.gradle:

buildscript {
    dependencies {
        // ...
        classpath 'com.bugsnag:bugsnag-android-gradle-plugin:4.+'
    }
}

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

apply plugin: 'com.android.application'
apply plugin: 'com.bugsnag.android.gradle'

dependencies {
    // ...
    implementation 'com.bugsnag:bugsnag-android:5.+'
}

Showing full stacktraces

The Bugsnag Gradle plugin (installed above) automatically handles deobfuscating file and method names. See the Android mapping guide for more details.

Basic configuration

This documentation is for version 5 of the Bugsnag Android notifier. If you are using older versions, we recommend upgrading to the latest release using our Upgrade guide. Documentation for the previous release can be found on our legacy pages.

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>

You can find your API key in Project Settings.

Initialize Bugsnag in the onCreate callback of your Application subclass:

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

If you’re creating a custom Application class for the first time, make sure to specify the subclass name in your AndroidManifest.xml:

<application
  android:name=".MyApp">
</application>

Note: If your app supports Android API 17 or lower, additional setup is required

If your supported minimum SDK version includes API 17 or lower, load the Bugsnag library before any libraries that link to it:

public class MyApp extends Application {
    static {
        System.loadLibrary("bugsnag-ndk");
        System.loadLibrary("bugsnag-plugin-android-anr");
        // ... (other libraries)
    }
    // ...
}
class MyApp : Application() {
    init {
        System.loadLibrary("bugsnag-ndk")
        System.loadLibrary("bugsnag-plugin-android-anr")
        // ... (other libraries)
    }
    // ...
}

Further configuration

If you’d like to configure Bugsnag further, check out the Configuration options reference.

Reporting unhandled exceptions

After completing installation and basic configuration, unhandled exceptions from Java or Kotlin will be automatically reported to your Bugsnag dashboard.

Reporting ANRs

When the main thread of an Android app is blocked for too long, it appears unresponsive and the Android OS creates an Application Not Responding (ANR) error, presenting the user with a dialog option to force quit the app.

ANR detection is enabled by default as part of the basic configuration steps. If you wish to disable it, see the enabledErrorTypes configuration option.

Reporting NDK errors

The Android Native Development Kit (NDK) is a toolset that lets you implement parts of your app in native code, using languages such as C and C++. Many third party libraries also include native code, even if your app does not do so directly.

NDK crash detection is enabled by default as part of the basic configuration steps. If you wish to disable it, see the enabledErrorTypes configuration option.

If you don’t require NDK error reporting you can exclude the bugsnag-plugin-android-ndk module to reduce the size of your app.

Native API configuration

The Native API is a collection of C and C++ helpers that allow you to report handled errors, leave breadcrumbs, and set user information. User information and breadcrumbs will be attached to all subsequent error reports from Java, Kotlin, and C/C++.

To use the Native API, update your CMakeLists.txt file to link the Bugsnag library:

add_library(lib_bugsnag SHARED IMPORTED)
# This directory is created automatically by the Bugsnag Gradle plugin
set(BUGSNAG_LIB_DIR
    ${CMAKE_SOURCE_DIR}/build/intermediates/bugsnag-libs)
set(BUGSNAG_INCLUDE_DIR ${BUGSNAG_LIB_DIR}/assets/include)
set_target_properties(lib_bugsnag PROPERTIES IMPORTED_LOCATION
                      ${BUGSNAG_LIB_DIR}/jni/${ANDROID_ABI}/libbugsnag-ndk.so)
# Insert your target name:
target_include_directories(your-native-lib PRIVATE ${BUGSNAG_INCLUDE_DIR})
target_link_libraries(your-native-lib lib_bugsnag)

Note: CMake rules differ for versions of Android Gradle Plugin < 3

If you are using an older version of Android Gradle Plugin, you should instead add the following to CMakeLists.txt:

add_library(lib_bugsnag SHARED IMPORTED)
set(BUGSNAG_VERSION 1.0.1)
set(BUGSNAG_DIR ${CMAKE_SOURCE_DIR}/build/intermediates/exploded-aar/com.bugsnag/bugsnag-android/${BUGSNAG_VERSION})
set_target_properties(lib_bugsnag PROPERTIES
    IMPORTED_LOCATION ${BUGSNAG_DIR}/jni/${ANDROID_ABI}/libbugsnag-ndk.so)
target_include_directories(your-native-lib PRIVATE ${BUGSNAG_DIR}/assets/include) # Insert your target name
target_link_libraries(your-native-lib lib_bugsnag) # Insert your target name

Once complete, you can invoke Bugsnag functions for reporting handled errors, leaving breadcrumbs, and setting user information. More information is provided in the sections below.

Reporting handled exceptions

If you would like to send handled exceptions to Bugsnag, you can pass any Throwable object to the Bugsnag.notify method. When reporting errors from C or C++ code, invoke bugsnag_notify_env with a name, message and severity.

try {
    // Some potentially crashy code
} catch (Throwable e) {
    Bugsnag.notify(e);
}
try {
    // Some potentially crashy code
} catch (e: Throwable) {
    Bugsnag.notify(e)
}
if (strlen(username) == 0) {
    // report failure to Bugsnag
    bugsnag_notify_env(env, "Validation Error",
                       "No name specified", BSG_SEVERITY_WARN);
}

Adding diagnostics or adjusting severity

It can often be helpful to adjust the severity or attach custom diagnostics to handled exceptions. For more information, see Reporting handled errors.

Sending diagnostic data

Automatically captured diagnostics

Bugsnag will automatically capture and attach the following diagnostic data to every error report:

  • Full stack traces for all threads.
  • App state including running time, time in foreground and active screen.
  • Build information including name, version/build and release stage.
  • Device specification including manufacturer, model, OS version, screen size/density and total memory.
  • System state including orientation, free memory, available disk space, battery level and network connectivity.

For more information see Automatically captured data.

Attaching custom diagnostics

It can often be helpful to attach application-specific diagnostic data to error reports. This can be accomplished by setting a callback which will be invoked before any reports are sent to Bugsnag:

Configuration config = Configuration.load(this);
config.addOnError(new OnErrorCallback() {
    @Override
    public boolean onError(Event event) {
        event.addMetadata("account", "name", "Acme Co.");
        event.addMetadata("account", "paying_customer", true);

        // Return `false` if you'd like to stop this error being reported
        return true;
    }
});
Bugsnag.start(this, config);
val config = Configuration.load(this)
config.addOnError(OnErrorCallback { event ->
    event.addMetadata("account", "name", "Acme Co.")
    event.addMetadata("account", "paying_customer", true)

    // Return `false` if you'd like to stop this error being reported
    true
})
Bugsnag.start(this, config)
bool custom_on_error_callback(void *event) {
    // Attach customer information to every error report
    bugsnag_event_add_metadata_string(event, "account", "name", "Acme Co.");
    bugsnag_event_add_metadata_bool(event, "account", "paying_customer", true);

    // Return `false` if you'd like to stop this error being reported
    return true;
}
bugsnag_add_on_error(&custom_on_error_callback);

For more information, see Customizing error reports.

Identifying users

In order to correlate errors with customer reports, or to see a list of users who experienced each error, it is helpful to capture and display user information. Bugsnag includes helpers attaching an identifier, email address, and name to reports that will be searchable in the dashboard:

Bugsnag.setUser("3", "bugs.nag@bugsnag.com", "Bugs Nag");
Bugsnag.setUser("3", "bugs.nag@bugsnag.com", "Bugs Nag")
bugsnag_set_user_env(env, "3", "bugs.nag@bugsnag.com", "Bugs Nag");

For more information, see Adding user data.

Logging breadcrumbs

In order to understand what happened in your application before each crash, it can be helpful to leave short log statements that we call breadcrumbs. A configurable number of breadcrumbs are attached to each error report to help diagnose what events led to the error.

Automatically captured breadcrumbs

By default, Bugsnag captures common events including:

  • Activity Lifecycle callbacks
  • Network connectivity changes
  • Bluetooth connectivity changes
  • Battery state changes
  • Device rotation
  • Media Scanner events
  • Telephony events
  • Other device metrics and more

Leaving custom breadcrumbs

You can use the leaveBreadcrumb method to log potentially useful events in your own applications:

Bugsnag.leaveBreadcrumb("App loaded");
Bugsnag.leaveBreadcrumb("User clicked a button");
Bugsnag.leaveBreadcrumb("App loaded")
Bugsnag.leaveBreadcrumb("User clicked a button")
bugsnag_leave_breadcrumb_env(env, "App loaded", BSG_CRUMB_MANUAL);

Bugsnag will keep track of the time and order of the breadcrumbs and show them on your dashboard.

Additional data can also be attached to breadcrumbs by providing the optional type and metadata parameters. For more information and examples for how custom breadcrumbs can be integrated, see Customizing breadcrumbs.

Session tracking

Bugsnag tracks the number of “sessions” that happen within your application. This allows you to compare stability scores between releases and helps you to understand the quality of your releases.

Sessions are captured and reported by default. This behavior can be disabled using the autoTrackSessions configuration option.

Bugsnag will automatically report a session each time an Activity is in the “Started” state and 30 seconds after all Activities have remained in the “Stopped” state.

For more information about manually controlling session tracking, see Capturing sessions.

Next steps