Out of Memory handling

The BugSnag Android SDK can be configured with dedicated and specialized handling for OutOfMemoryError runtime errors.

An OutOfMemoryError typically requires more delicate handling than other types of crash. When the Android Runtime runs out of memory it often means there is not enough memory for the SDK to allocate an error report. BugSnag Android therefore contains a specialized OutOfMemoryHandler callback which allows more sophisticated interactions with the error reporting to reduce the chances that an OutOfMemoryError is lost.

When an OutOfMemoryError is detected, if you have configured an OutOfMemoryHandler it will be called before any Bugsnag event is generated. This allows you to either release some memory or take over handling of the OutOfMemoryError.

Custom OutOfMemoryError handling

The OutOfMemoryHandler callback can used either to augment and support the standard BugSnag error reporting, or to entirely replace it:

byte[] bigMemoryBuffer = new byte[10 * 1024 * 1024];

Bugsnag.setOutOfMemoryHandler((OutOfMemoryError oom) -> {
    bigMemoryBuffer = null;
    // continue to handle the OutOfMemoryError normally
    // returning true here "consumes" the OutOfMemoryError
    return false;
});
var bigMemoryBuffer: ByteArray? = ByteArray(10 * 1024 * 1024)

Bugsnag.setOutOfMemoryHandler { oom ->
    bigMemoryBuffer = null
    // continue to handle the OutOfMemoryError normally
    // returning true here "consumes" the OutOfMemoryError
    false
}

Pre-allocated handler plugin

The bugsnag-plugin-android-ndk module pre-allocates memory for a crash during startup which can be used specifically for OutOfMemoryError reporting via the NativeOutOfMemoryPlugin. This avoids nearly all allocations required to report the OutOfMemoryError by side-stepping the usual Android Runtime (ART) crash handling. Adding this plugin will replace the SDK’s OutOfMemoryHandler as described above.

Installation

Ensure that bugsnag-plugin-android-ndk is direct dependency of your app by adding the dependency to your app/build.gradle or build.gradle.kts file:

dependencies {
  implementation("com.bugsnag:bugsnag-plugin-android-ndk:6.+")
}
dependencies {
  implementation("com.bugsnag:bugsnag-plugin-android-ndk:6.+")
}

Then add the plugin to your configuration:

Configuration config = Configuration.load(this);
config.addPlugin(new NativeOutOfMemoryPlugin());
Bugsnag.start(this, config);
Bugsnag.start(this, Configuration.load(this).apply {
  addPlugin(NativeOutOfMemoryPlugin())
})

Because NativeOutOfMemoryPlugin moves the OutOfMemoryError reporting to the NDK module, no OnErrorCallbacks will be triggered when reporting an OutOfMemoryError when this plugin is used. Other crash reporting remains unaffected, and OnSendCallbacks will work as expected.