diff --git a/CHANGELOG.md b/CHANGELOG.md
index 69ddbc590bf..f9e79b7262a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,12 @@
- Android: A crash long after `Sentry.init` is no longer marked as a startup crash when the device slept in between, because the time since init now counts deep sleep ([#6738](https://github.com/getsentry/sentry-java/pull/6738))
+### Features
+
+- Record ANR warnings from the system as `app.anr` breadcrumbs on Android 17 (API 37) and above ([#6245](https://github.com/getsentry/sentry-java/pull/6245))
+ - The breadcrumb contains the ANR type, the system description, the timeout, and how much of the timeout was already used.
+ - It is enabled by default. To disable it, set `options.isEnableAnrWarningBreadcrumbs = false` or add `` to your `AndroidManifest.xml`.
+
### Dependencies
- Bump OpenTelemetry ([#6691](https://github.com/getsentry/sentry-java/pull/6691))
diff --git a/build-logic/src/main/kotlin/io/sentry/gradle/JdkTargetConvention.kt b/build-logic/src/main/kotlin/io/sentry/gradle/JdkTargetConvention.kt
index 0b4c54ce906..4cac747feaa 100644
--- a/build-logic/src/main/kotlin/io/sentry/gradle/JdkTargetConvention.kt
+++ b/build-logic/src/main/kotlin/io/sentry/gradle/JdkTargetConvention.kt
@@ -10,6 +10,7 @@ import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.compile.JavaCompile
+import org.gradle.api.tasks.testing.Test
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension
@@ -110,7 +111,18 @@ class JdkTargetConvention : Plugin {
}
listOf("com.android.library", "com.android.application").forEach { pluginId ->
- project.plugins.withId(pluginId) { project.targetBuildJdkForUnitTests() }
+ project.plugins.withId(pluginId) {
+ project.targetBuildJdkForUnitTests()
+ // Robolectric's SDK 37 sandbox (the default, as targetSdk is 37) reflectively writes
+ // FileDescriptor fields in ApplicationSharedMemory; without this, setup fails with
+ // "Failed to interact with raw FileDescriptor internals".
+ project.tasks.withType(Test::class.java).configureEach {
+ jvmArgs(
+ "--add-opens=java.base/java.io=ALL-UNNAMED",
+ "--add-exports=java.base/jdk.internal.access=ALL-UNNAMED",
+ )
+ }
+ }
}
}
diff --git a/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt b/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt
index a996574f7da..0d22ce9b78d 100644
--- a/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt
+++ b/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt
@@ -26,14 +26,15 @@ import org.gradle.work.DisableCachingByDefault
*/
private val ANDROID_ALL_VERSIONS =
mapOf(
- 21 to "5.0.2_r3-robolectric-r0",
+ 23 to "6.0.1_r3-robolectric-r1",
24 to "7.0.0_r1-robolectric-r1",
28 to "9-robolectric-4913185-2",
29 to "10-robolectric-5803371",
30 to "11-robolectric-6757853",
31 to "12-robolectric-7732740",
33 to "13-robolectric-9030017",
- 35 to "15-robolectric-12650502",
+ 35 to "15-robolectric-13954326",
+ 37 to "17-robolectric-15733970",
)
/** The instrumentation revision Robolectric appends to every android-all version. */
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 22527c4c997..c421079b912 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -316,7 +316,7 @@ okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp
okio = { module = "com.squareup.okio:okio", version = "3.18.2" }
rhino = { module = "org.mozilla:rhino", version = "1.8.0" }
# Upgrading Robolectric can change the android-all jars it needs, see SentryRobolectricPlugin.
-roboelectric = { module = "org.robolectric:robolectric", version = "4.15" }
+roboelectric = { module = "org.robolectric:robolectric", version = "4.17" }
[bundles]
androidx-room2 = ["androidx-room-runtime", "androidx-room-ktx"]
diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api
index a4810fa52ae..147f9cd440e 100644
--- a/sentry-android-core/api/sentry-android-core.api
+++ b/sentry-android-core/api/sentry-android-core.api
@@ -174,6 +174,12 @@ public final class io/sentry/android/core/AnrV2Integration$AnrV2Hint : io/sentry
public fun timestamp ()Ljava/lang/Long;
}
+public final class io/sentry/android/core/AnrWarningListenerIntegration : io/sentry/Integration, java/io/Closeable {
+ public fun (Landroid/content/Context;Lio/sentry/android/core/BuildInfoProvider;)V
+ public fun close ()V
+ public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
+}
+
public final class io/sentry/android/core/AppComponentsBreadcrumbsIntegration : android/content/ComponentCallbacks2, io/sentry/Integration, java/io/Closeable {
public fun (Landroid/content/Context;)V
public fun close ()V
@@ -459,6 +465,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun isEnableActivityLifecycleBreadcrumbs ()Z
public fun isEnableActivityLifecycleTracingAutoFinish ()Z
public fun isEnableAnrFingerprinting ()Z
+ public fun isEnableAnrWarningBreadcrumbs ()Z
public fun isEnableAppComponentBreadcrumbs ()Z
public fun isEnableAppLifecycleBreadcrumbs ()Z
public fun isEnableAutoActivityLifecycleTracing ()Z
@@ -494,6 +501,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun setEnableActivityLifecycleBreadcrumbs (Z)V
public fun setEnableActivityLifecycleTracingAutoFinish (Z)V
public fun setEnableAnrFingerprinting (Z)V
+ public fun setEnableAnrWarningBreadcrumbs (Z)V
public fun setEnableAppComponentBreadcrumbs (Z)V
public fun setEnableAppLifecycleBreadcrumbs (Z)V
public fun setEnableAutoActivityLifecycleTracing (Z)V
diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java
index 52a54b339dc..7ba96e646f6 100644
--- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java
+++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java
@@ -474,6 +474,7 @@ static void installDefaultIntegrations(
options.addIntegration(AnrIntegrationFactory.create(context, buildInfoProvider));
options.addIntegration(new AnrProfilingIntegration());
+ options.addIntegration(new AnrWarningListenerIntegration(context, buildInfoProvider));
// registerActivityLifecycleCallbacks is only available if Context is an AppContext
if (context instanceof Application) {
diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AnrWarningListenerIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrWarningListenerIntegration.java
new file mode 100644
index 00000000000..ee185f1daf2
--- /dev/null
+++ b/sentry-android-core/src/main/java/io/sentry/android/core/AnrWarningListenerIntegration.java
@@ -0,0 +1,307 @@
+package io.sentry.android.core;
+
+import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion;
+
+import android.annotation.SuppressLint;
+import android.app.ActivityManager;
+import android.app.AnrTypes;
+import android.app.AnrWarningResult;
+import android.content.Context;
+import android.os.Build;
+import androidx.annotation.RequiresApi;
+import io.sentry.Breadcrumb;
+import io.sentry.IScopes;
+import io.sentry.ISentryLifecycleToken;
+import io.sentry.Integration;
+import io.sentry.SentryLevel;
+import io.sentry.SentryOptions;
+import io.sentry.util.AutoClosableReentrantLock;
+import io.sentry.util.ExceptionUtils;
+import io.sentry.util.Objects;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.function.Consumer;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Adds an {@code app.anr} breadcrumb for each ANR warning that the system reports through {@link
+ * ActivityManager#registerAnrWarningListener} on Android 17 (API 37) and above. The system sends
+ * the warning while the ANR timeout is still running, before the app is declared unresponsive.
+ */
+public final class AnrWarningListenerIntegration implements Integration, Closeable {
+
+ private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock();
+ private final @NotNull Context context;
+ private final @NotNull BuildInfoProvider buildInfoProvider;
+
+ private @Nullable SentryAndroidOptions options;
+ private @Nullable AnrWarningBreadcrumbConsumer anrWarningConsumer;
+ private boolean isClosed;
+
+ public AnrWarningListenerIntegration(
+ final @NotNull Context context, final @NotNull BuildInfoProvider buildInfoProvider) {
+ this.context = ContextUtils.getApplicationContext(context);
+ this.buildInfoProvider = buildInfoProvider;
+ }
+
+ @Override
+ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) {
+ Objects.requireNonNull(scopes, "Scopes are required");
+ final @NotNull SentryAndroidOptions androidOptions =
+ Objects.requireNonNull(
+ (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
+ "SentryAndroidOptions is required");
+ this.options = androidOptions;
+
+ androidOptions
+ .getLogger()
+ .log(
+ SentryLevel.DEBUG,
+ "enableAnrWarningBreadcrumbs enabled: %s",
+ androidOptions.isEnableAnrWarningBreadcrumbs());
+
+ if (androidOptions.isEnableAnrWarningBreadcrumbs()) {
+ scheduleRegisterAnrWarningListener(scopes, androidOptions);
+ }
+ }
+
+ /**
+ * {@link ActivityManager#registerAnrWarningListener} is a binder call, so it must not run on the
+ * caller's thread — {@link #register} is driven from {@code Sentry.init} on the main thread.
+ */
+ @SuppressWarnings("FutureReturnValueIgnored")
+ private void scheduleRegisterAnrWarningListener(
+ final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) {
+ if (buildInfoProvider.getSdkInfoVersion() < Build.VERSION_CODES.CINNAMON_BUN) {
+ options
+ .getLogger()
+ .log(SentryLevel.DEBUG, "ANR warning listener needs Android API 37 and above.");
+ return;
+ }
+
+ try {
+ options
+ .getExecutorService()
+ .submit(() -> registerAnrWarningListener(context, scopes, options));
+ addIntegrationToSdkVersion("AnrWarningListener");
+ } catch (RejectedExecutionException e) {
+ options
+ .getLogger()
+ .log(
+ SentryLevel.WARNING,
+ "Failed to submit the ANR warning listener registration to the executor service.",
+ e);
+ }
+ }
+
+ private void scheduleUnregisterAnrWarningListener() {
+ final @Nullable SentryAndroidOptions options = this.options;
+ if (options == null) {
+ return;
+ }
+
+ // unregisterAnrWarningListener is idempotent, so running it twice after a dropped task is
+ // harmless, whereas never running it would leak the listener for the process lifetime.
+ try {
+ final @NotNull Future> future =
+ options.getExecutorService().submit(() -> unregisterAnrWarningListener(options));
+ if (future.isCancelled()) {
+ unregisterAnrWarningListener(options);
+ }
+ } catch (RejectedExecutionException e) {
+ unregisterAnrWarningListener(options);
+ }
+ }
+
+ /** Runs on the executor service. Guarded by {@link #scheduleRegisterAnrWarningListener}. */
+ // Lint cannot see through buildInfoProvider, which scheduleRegisterAnrWarningListener checks
+ // before this ever runs. The suppression is scoped so that register() stays lint-checked.
+ @SuppressLint("NewApi")
+ private void registerAnrWarningListener(
+ final @NotNull Context context,
+ final @NotNull IScopes scopes,
+ final @NotNull SentryAndroidOptions options) {
+ final @Nullable ActivityManager activityManager =
+ (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
+ if (activityManager == null) {
+ options
+ .getLogger()
+ .log(
+ SentryLevel.INFO,
+ "ActivityManager is not available, ANR warning listener not installed.");
+ return;
+ }
+
+ final @NotNull AnrWarningBreadcrumbConsumer consumer = new AnrWarningBreadcrumbConsumer(scopes);
+
+ try (final ISentryLifecycleToken ignored = lock.acquire()) {
+ if (isClosed || anrWarningConsumer != null) {
+ return;
+ }
+ }
+
+ // The binder call runs without the lock, so that close() never waits for the system.
+ try {
+ activityManager.registerAnrWarningListener(Runnable::run, consumer);
+ } catch (RuntimeException e) {
+ // Broad catch, because a call into the system server can throw any RuntimeException. On
+ // failure the listener is not installed, so no app.anr breadcrumbs are recorded.
+ ExceptionUtils.rethrowIfFatal(e);
+ options
+ .getLogger()
+ .log(SentryLevel.WARNING, "Failed to register the ANR warning listener.", e);
+ return;
+ }
+
+ final boolean closedDuringRegistration;
+ try (final ISentryLifecycleToken ignored = lock.acquire()) {
+ closedDuringRegistration = isClosed;
+ if (!closedDuringRegistration) {
+ anrWarningConsumer = consumer;
+ }
+ }
+ if (closedDuringRegistration) {
+ consumer.detach();
+ unregisterAnrWarningListener(activityManager, consumer, options);
+ return;
+ }
+
+ options.getLogger().log(SentryLevel.DEBUG, "ANR warning listener installed.");
+ }
+
+ @SuppressLint("NewApi")
+ private void unregisterAnrWarningListener(final @NotNull SentryAndroidOptions options) {
+ final @Nullable Consumer consumerRef;
+ try (final ISentryLifecycleToken ignored = lock.acquire()) {
+ consumerRef = anrWarningConsumer;
+ anrWarningConsumer = null;
+ }
+
+ if (consumerRef == null) {
+ return;
+ }
+
+ final @Nullable ActivityManager activityManager =
+ (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
+ if (activityManager == null) {
+ options
+ .getLogger()
+ .log(
+ SentryLevel.INFO,
+ "ActivityManager is not available, ANR warning listener not unregistered.");
+ return;
+ }
+ unregisterAnrWarningListener(activityManager, consumerRef, options);
+ }
+
+ @SuppressLint("NewApi")
+ private static void unregisterAnrWarningListener(
+ final @NotNull ActivityManager activityManager,
+ final @NotNull Consumer consumer,
+ final @NotNull SentryAndroidOptions options) {
+ try {
+ activityManager.unregisterAnrWarningListener(consumer);
+ } catch (RuntimeException e) {
+ // Broad catch, because a call into the system server can throw any RuntimeException. On
+ // failure the listener stays registered until the process ends.
+ ExceptionUtils.rethrowIfFatal(e);
+ options
+ .getLogger()
+ .log(SentryLevel.WARNING, "Failed to unregister the ANR warning listener.", e);
+ }
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.CINNAMON_BUN)
+ static @NotNull Breadcrumb createAnrBreadcrumb(final @NotNull AnrWarningResult result) {
+ final Breadcrumb breadcrumb = new Breadcrumb();
+ breadcrumb.setType("system");
+ breadcrumb.setCategory("app.anr");
+ breadcrumb.setLevel(SentryLevel.WARNING);
+ breadcrumb.setMessage("ANR warning");
+ breadcrumb.setData("anr_type", getAnrTypeName(result.getAnrType()));
+ breadcrumb.setData("anr_id", result.getAnrId());
+ breadcrumb.setData("timeout_ms", result.getTimeoutMillis());
+ breadcrumb.setData("consumed_ms", result.getConsumedMillis());
+ // The system already strips sensitive data: a broadcast ANR describes its Intent with
+ // Intent.toString(), which redacts the data URI (Uri.toSafeString()) and omits extra values.
+ // The system leaves this empty for some ANR types, so do not carry a blank value.
+ final @Nullable String description = result.getDescription();
+ if (description != null && !description.isEmpty()) {
+ breadcrumb.setData("description", description);
+ }
+ return breadcrumb;
+ }
+
+ // AnrTypes only holds compile-time int constants, which javac inlines, so this needs no
+ // runtime API 37 symbol and stays callable (and testable) on every API level.
+ @SuppressLint("NewApi")
+ static @NotNull String getAnrTypeName(final int anrType) {
+ switch (anrType) {
+ case AnrTypes.ANR_TYPE_OTHER:
+ return "other";
+ case AnrTypes.ANR_TYPE_INPUT_DISPATCH_NO_FOCUSED_WINDOW:
+ return "input_dispatch_no_focused_window";
+ case AnrTypes.ANR_TYPE_INPUT_DISPATCH:
+ return "input_dispatch";
+ case AnrTypes.ANR_TYPE_BROADCAST_OF_INTENT:
+ return "broadcast_of_intent";
+ case AnrTypes.ANR_TYPE_START_FOREGROUND_SERVICE:
+ return "start_foreground_service";
+ case AnrTypes.ANR_TYPE_EXECUTE_SERVICE:
+ return "execute_service";
+ case AnrTypes.ANR_TYPE_CONTENT_PROVIDER_NOT_RESPONDING:
+ return "content_provider_not_responding";
+ case AnrTypes.ANR_TYPE_APP_TRIGGERED:
+ return "app_triggered";
+ case AnrTypes.ANR_TYPE_FOREGROUND_SHORT_SERVICE_TIMEOUT:
+ return "foreground_short_service_timeout";
+ case AnrTypes.ANR_TYPE_JOB_SERVICE_START:
+ return "job_service_start";
+ case AnrTypes.ANR_TYPE_APPLICATION_START:
+ return "application_start";
+ default:
+ return "unknown (" + anrType + ")";
+ }
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.CINNAMON_BUN)
+ static final class AnrWarningBreadcrumbConsumer implements Consumer {
+ private volatile @Nullable IScopes scopes;
+
+ AnrWarningBreadcrumbConsumer(final @NotNull IScopes scopes) {
+ this.scopes = scopes;
+ }
+
+ void detach() {
+ scopes = null;
+ }
+
+ @Override
+ public void accept(final @NotNull AnrWarningResult result) {
+ final @Nullable IScopes scopesRef = scopes;
+ if (scopesRef != null) {
+ scopesRef.addBreadcrumb(createAnrBreadcrumb(result));
+ }
+ }
+ }
+
+ // anrWarningConsumer is only set by registerAnrWarningListener, which runs on API 37 and above.
+ @SuppressLint("NewApi")
+ @Override
+ public void close() throws IOException {
+ try (final ISentryLifecycleToken ignored = lock.acquire()) {
+ // Set before scheduling the unregister, so a register task that is still queued bails out
+ // instead of resurrecting the listener after close.
+ isClosed = true;
+ // Detached here, not in the unregister task: if executor shutdown drops that task, the
+ // system keeps the listener, but it no longer holds the scopes of the closed SDK.
+ if (anrWarningConsumer != null) {
+ anrWarningConsumer.detach();
+ }
+ }
+ scheduleUnregisterAnrWarningListener();
+ }
+}
diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java
index da60741a4c9..ca5bb96c2fe 100644
--- a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java
+++ b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java
@@ -75,6 +75,7 @@ final class ManifestMetadataReader {
static final String BREADCRUMBS_ACTIVITY_LIFECYCLE_ENABLE =
"io.sentry.breadcrumbs.activity-lifecycle";
static final String BREADCRUMBS_APP_LIFECYCLE_ENABLE = "io.sentry.breadcrumbs.app-lifecycle";
+ static final String BREADCRUMBS_ANR_WARNINGS_ENABLE = "io.sentry.breadcrumbs.anr-warnings";
static final String BREADCRUMBS_SYSTEM_EVENTS_ENABLE = "io.sentry.breadcrumbs.system-events";
static final String BREADCRUMBS_NETWORK_EVENTS_ENABLE = "io.sentry.breadcrumbs.network-events";
static final String BREADCRUMBS_APP_COMPONENTS_ENABLE = "io.sentry.breadcrumbs.app-components";
@@ -401,6 +402,13 @@ static void applyMetadata(
BREADCRUMBS_APP_LIFECYCLE_ENABLE,
options.isEnableAppLifecycleBreadcrumbs()));
+ options.setEnableAnrWarningBreadcrumbs(
+ readBool(
+ metadata,
+ logger,
+ BREADCRUMBS_ANR_WARNINGS_ENABLE,
+ options.isEnableAnrWarningBreadcrumbs()));
+
options.setEnableSystemEventBreadcrumbs(
readBool(
metadata,
diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java
index 2afb245fe38..92ff4b934f8 100644
--- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java
+++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java
@@ -69,6 +69,12 @@ public final class SentryAndroidOptions extends SentryOptions {
/** Enable or disable automatic breadcrumbs for SystemEvents Registering a BroadcastReceiver */
private boolean enableSystemEventBreadcrumbs = true;
+ /**
+ * Enable or disable automatic {@code app.anr} breadcrumbs for the ANR warnings that the system
+ * reports on Android 17 (API 37) and above, before the app is declared unresponsive.
+ */
+ private boolean enableAnrWarningBreadcrumbs = true;
+
/** Enable or disable automatic breadcrumbs for App Components Using ComponentCallbacks */
private boolean enableAppComponentBreadcrumbs = true;
@@ -485,6 +491,14 @@ public void setEnableAppLifecycleBreadcrumbs(boolean enableAppLifecycleBreadcrum
this.enableAppLifecycleBreadcrumbs = enableAppLifecycleBreadcrumbs;
}
+ public boolean isEnableAnrWarningBreadcrumbs() {
+ return enableAnrWarningBreadcrumbs;
+ }
+
+ public void setEnableAnrWarningBreadcrumbs(boolean enableAnrWarningBreadcrumbs) {
+ this.enableAnrWarningBreadcrumbs = enableAnrWarningBreadcrumbs;
+ }
+
public boolean isEnableSystemEventBreadcrumbs() {
return enableSystemEventBreadcrumbs;
}
@@ -519,6 +533,7 @@ public void enableAllAutoBreadcrumbs(boolean enable) {
enableAppComponentBreadcrumbs = enable;
enableSystemEventBreadcrumbs = enable;
enableAppLifecycleBreadcrumbs = enable;
+ enableAnrWarningBreadcrumbs = enable;
enableNetworkEventBreadcrumbs = enable;
setEnableUserInteractionBreadcrumbs(enable);
}
diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt
index 226ea753977..9964f61890a 100644
--- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt
+++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt
@@ -672,6 +672,15 @@ class AndroidOptionsInitializerTest {
assertNotNull(actual)
}
+ @Test
+ fun `AnrWarningListenerIntegration added to integration list`() {
+ fixture.initSut()
+
+ val actual =
+ fixture.sentryOptions.integrations.firstOrNull { it is AnrWarningListenerIntegration }
+ assertNotNull(actual)
+ }
+
@Test
fun `AnrIntegration is added after AppLifecycleIntegration`() {
fixture.initSut()
diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AnrWarningListenerIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AnrWarningListenerIntegrationTest.kt
new file mode 100644
index 00000000000..74d34559297
--- /dev/null
+++ b/sentry-android-core/src/test/java/io/sentry/android/core/AnrWarningListenerIntegrationTest.kt
@@ -0,0 +1,348 @@
+package io.sentry.android.core
+
+import android.app.ActivityManager
+import android.app.AnrTypes
+import android.app.AnrWarningResult
+import android.app.Application
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import io.sentry.Breadcrumb
+import io.sentry.IScopes
+import io.sentry.ISentryExecutorService
+import io.sentry.SentryLevel
+import io.sentry.test.DeferredExecutorService
+import io.sentry.test.ImmediateExecutorService
+import io.sentry.test.NonOverridableNoOpSentryExecutorService
+import java.util.function.Consumer
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+import org.junit.runner.RunWith
+import org.mockito.kotlin.any
+import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.check
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.times
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+
+@RunWith(AndroidJUnit4::class)
+class AnrWarningListenerIntegrationTest {
+ private class Fixture {
+ val scopes = mock()
+ val options = SentryAndroidOptions()
+ }
+
+ private val fixture = Fixture()
+
+ /**
+ * Robolectric has no shadow for registerAnrWarningListener and offers no way to deliver a
+ * warning, so the ActivityManager itself is mocked. Everything around it is real: the mock is
+ * injected into the Robolectric application context as the system service.
+ */
+ private fun getSutWithActivityManager(
+ activityManager: ActivityManager,
+ sdkVersion: Int = 37,
+ executorService: ISentryExecutorService = ImmediateExecutorService(),
+ ): AnrWarningListenerIntegration {
+ val application = ApplicationProvider.getApplicationContext()
+ shadowOf(application).setSystemService(Context.ACTIVITY_SERVICE, activityManager)
+ val buildInfoProvider = mock()
+ whenever(buildInfoProvider.sdkInfoVersion).thenReturn(sdkVersion)
+ fixture.options.executorService = executorService
+ return AnrWarningListenerIntegration(application, buildInfoProvider)
+ }
+
+ private fun anrWarningResult(
+ anrType: Int = AnrTypes.ANR_TYPE_BROADCAST_OF_INTENT,
+ anrId: Int = 7,
+ description: String? = "Broadcast of Intent { act=android.intent.action.SCREEN_ON }",
+ timeoutMillis: Long = 10_000,
+ consumedMillis: Long = 7_500,
+ ): AnrWarningResult =
+ mock().also {
+ whenever(it.anrType).thenReturn(anrType)
+ whenever(it.anrId).thenReturn(anrId)
+ whenever(it.description).thenReturn(description)
+ whenever(it.timeoutMillis).thenReturn(timeoutMillis)
+ whenever(it.consumedMillis).thenReturn(consumedMillis)
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `ANR warning listener adds a breadcrumb and is unregistered on close`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+
+ sut.register(fixture.scopes, fixture.options)
+
+ val consumerCaptor = argumentCaptor>()
+ verify(activityManager).registerAnrWarningListener(any(), consumerCaptor.capture())
+
+ consumerCaptor.firstValue.accept(anrWarningResult())
+
+ verify(fixture.scopes)
+ .addBreadcrumb(
+ check {
+ assertEquals("system", it.type)
+ assertEquals("app.anr", it.category)
+ assertEquals(SentryLevel.WARNING, it.level)
+ assertEquals("ANR warning", it.message)
+ assertEquals("broadcast_of_intent", it.getData("anr_type"))
+ assertEquals(7, it.getData("anr_id"))
+ assertEquals(10_000L, it.getData("timeout_ms"))
+ assertEquals(7_500L, it.getData("consumed_ms"))
+ assertEquals(
+ "Broadcast of Intent { act=android.intent.action.SCREEN_ON }",
+ it.getData("description"),
+ )
+ },
+ )
+
+ sut.close()
+
+ verify(activityManager).unregisterAnrWarningListener(consumerCaptor.firstValue)
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `a listener left registered after close no longer adds breadcrumbs`() {
+ val activityManager = mock()
+ val executorService = DeferredExecutorService()
+ val sut = getSutWithActivityManager(activityManager, executorService = executorService)
+
+ sut.register(fixture.scopes, fixture.options)
+ executorService.runAll()
+ val consumerCaptor = argumentCaptor>()
+ verify(activityManager).registerAnrWarningListener(any(), consumerCaptor.capture())
+
+ // The unregister task is never run, as when executor shutdown drops it.
+ sut.close()
+ consumerCaptor.firstValue.accept(anrWarningResult())
+
+ verify(activityManager, never()).unregisterAnrWarningListener(any())
+ verify(fixture.scopes, never()).addBreadcrumb(any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `unknown ANR types are reported verbatim instead of being dropped`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+
+ sut.register(fixture.scopes, fixture.options)
+
+ val consumerCaptor = argumentCaptor>()
+ verify(activityManager).registerAnrWarningListener(any(), consumerCaptor.capture())
+ consumerCaptor.firstValue.accept(anrWarningResult(anrType = 42))
+
+ verify(fixture.scopes)
+ .addBreadcrumb(check { assertEquals("unknown (42)", it.getData("anr_type")) })
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `ANR warning listener is not registered when ANR warning breadcrumbs are disabled`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+ fixture.options.isEnableAnrWarningBreadcrumbs = false
+
+ sut.register(fixture.scopes, fixture.options)
+
+ verify(activityManager, never()).registerAnrWarningListener(any(), any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `ANR warning listener is not registered below API 37`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager, sdkVersion = 36)
+
+ sut.register(fixture.scopes, fixture.options)
+
+ verify(activityManager, never()).registerAnrWarningListener(any(), any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `a failure to register the ANR warning listener is not unregistered on close`() {
+ val activityManager = mock()
+ whenever(activityManager.registerAnrWarningListener(any(), any()))
+ .thenThrow(RuntimeException("binder died"))
+ val sut = getSutWithActivityManager(activityManager)
+
+ sut.register(fixture.scopes, fixture.options)
+ sut.close()
+
+ verify(activityManager, never()).unregisterAnrWarningListener(any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `closing twice unregisters the ANR warning listener only once`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+
+ sut.register(fixture.scopes, fixture.options)
+ sut.close()
+ sut.close()
+
+ verify(activityManager, times(1)).unregisterAnrWarningListener(any())
+ }
+
+ @Test
+ fun `ANR type names are mapped`() {
+ assertEquals("other", AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_OTHER))
+ assertEquals(
+ "input_dispatch_no_focused_window",
+ AnrWarningListenerIntegration.getAnrTypeName(
+ AnrTypes.ANR_TYPE_INPUT_DISPATCH_NO_FOCUSED_WINDOW,
+ ),
+ )
+ assertEquals(
+ "broadcast_of_intent",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_BROADCAST_OF_INTENT),
+ )
+ assertEquals(
+ "start_foreground_service",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_START_FOREGROUND_SERVICE),
+ )
+ assertEquals(
+ "execute_service",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_EXECUTE_SERVICE),
+ )
+ assertEquals(
+ "content_provider_not_responding",
+ AnrWarningListenerIntegration.getAnrTypeName(
+ AnrTypes.ANR_TYPE_CONTENT_PROVIDER_NOT_RESPONDING,
+ ),
+ )
+ assertEquals(
+ "app_triggered",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_APP_TRIGGERED),
+ )
+ assertEquals(
+ "foreground_short_service_timeout",
+ AnrWarningListenerIntegration.getAnrTypeName(
+ AnrTypes.ANR_TYPE_FOREGROUND_SHORT_SERVICE_TIMEOUT,
+ ),
+ )
+ assertEquals(
+ "job_service_start",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_JOB_SERVICE_START),
+ )
+ assertEquals(
+ "application_start",
+ AnrWarningListenerIntegration.getAnrTypeName(AnrTypes.ANR_TYPE_APPLICATION_START),
+ )
+ assertEquals("unknown (42)", AnrWarningListenerIntegration.getAnrTypeName(42))
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `the binder calls run on the executor service, not on the calling thread`() {
+ val activityManager = mock()
+ val executorService = DeferredExecutorService()
+ val sut = getSutWithActivityManager(activityManager, executorService = executorService)
+
+ sut.register(fixture.scopes, fixture.options)
+ verify(activityManager, never()).registerAnrWarningListener(any(), any())
+
+ executorService.runAll()
+ verify(activityManager).registerAnrWarningListener(any(), any())
+
+ sut.close()
+ verify(activityManager, never()).unregisterAnrWarningListener(any())
+
+ executorService.runAll()
+ verify(activityManager).unregisterAnrWarningListener(any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `a register task still queued when close runs does not register the listener`() {
+ val activityManager = mock()
+ val executorService = DeferredExecutorService()
+ val sut = getSutWithActivityManager(activityManager, executorService = executorService)
+
+ sut.register(fixture.scopes, fixture.options)
+ sut.close()
+ executorService.runAll()
+
+ verify(activityManager, never()).registerAnrWarningListener(any(), any())
+ verify(activityManager, never()).unregisterAnrWarningListener(any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `close does not wait for a running registration, which then unregisters the listener`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+ var closeReturned = false
+ whenever(activityManager.registerAnrWarningListener(any(), any())).then {
+ val closingThread = Thread { sut.close() }
+ closingThread.start()
+ closingThread.join(5_000)
+ closeReturned = !closingThread.isAlive
+ null
+ }
+
+ sut.register(fixture.scopes, fixture.options)
+
+ assertTrue(closeReturned)
+ val consumer = argumentCaptor>()
+ verify(activityManager).registerAnrWarningListener(any(), consumer.capture())
+ verify(activityManager).unregisterAnrWarningListener(consumer.firstValue)
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `ANR warning listener is registered when the Context has no application context`() {
+ val activityManager = mock()
+ val context = mock()
+ whenever(context.getSystemService(Context.ACTIVITY_SERVICE)).thenReturn(activityManager)
+ val buildInfoProvider = mock()
+ whenever(buildInfoProvider.sdkInfoVersion).thenReturn(37)
+ fixture.options.executorService = ImmediateExecutorService()
+ val sut = AnrWarningListenerIntegration(context, buildInfoProvider)
+
+ sut.register(fixture.scopes, fixture.options)
+
+ verify(activityManager).registerAnrWarningListener(any(), any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `a dropped register task leaves the listener uninstalled`() {
+ val activityManager = mock()
+ val sut =
+ getSutWithActivityManager(
+ activityManager,
+ executorService = NonOverridableNoOpSentryExecutorService(),
+ )
+
+ sut.register(fixture.scopes, fixture.options)
+
+ verify(activityManager, never()).registerAnrWarningListener(any(), any())
+ }
+
+ @Test
+ @Config(sdk = [37])
+ fun `close unregisters inline when the executor service drops the task`() {
+ val activityManager = mock()
+ val sut = getSutWithActivityManager(activityManager)
+
+ sut.register(fixture.scopes, fixture.options)
+ verify(activityManager).registerAnrWarningListener(any(), any())
+
+ // The executor is typically already shut down by the time integrations are closed.
+ fixture.options.executorService = NonOverridableNoOpSentryExecutorService()
+ sut.close()
+
+ verify(activityManager).unregisterAnrWarningListener(any())
+ }
+}
diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt
index a6a3f1f34fd..2fce231c4ed 100644
--- a/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt
+++ b/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt
@@ -584,6 +584,31 @@ class ManifestMetadataReaderTest {
assertTrue(fixture.options.isEnableAppLifecycleBreadcrumbs)
}
+ @Test
+ fun `applyMetadata reads ANR warning breadcrumbs to options`() {
+ // Arrange
+ val bundle = bundleOf(ManifestMetadataReader.BREADCRUMBS_ANR_WARNINGS_ENABLE to false)
+ val context = fixture.getContext(metaData = bundle)
+
+ // Act
+ ManifestMetadataReader.applyMetadata(context, fixture.options, fixture.buildInfoProvider)
+
+ // Assert
+ assertFalse(fixture.options.isEnableAnrWarningBreadcrumbs)
+ }
+
+ @Test
+ fun `applyMetadata reads ANR warning breadcrumbs and keep default value if not found`() {
+ // Arrange
+ val context = fixture.getContext()
+
+ // Act
+ ManifestMetadataReader.applyMetadata(context, fixture.options, fixture.buildInfoProvider)
+
+ // Assert
+ assertTrue(fixture.options.isEnableAnrWarningBreadcrumbs)
+ }
+
@Test
fun `applyMetadata reads system events breadcrumbs to options`() {
// Arrange
diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt
index 0934ab97a5f..c81ff89799b 100644
--- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt
+++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt
@@ -187,6 +187,22 @@ class SentryAndroidOptionsTest {
)
}
+ @Test
+ fun `ANR warning breadcrumbs are enabled by default`() {
+ assertTrue(SentryAndroidOptions().isEnableAnrWarningBreadcrumbs)
+ }
+
+ @Test
+ fun `enableAllAutoBreadcrumbs also switches ANR warning breadcrumbs`() {
+ val sentryOptions = SentryAndroidOptions()
+
+ sentryOptions.enableAllAutoBreadcrumbs(false)
+ assertFalse(sentryOptions.isEnableAnrWarningBreadcrumbs)
+
+ sentryOptions.enableAllAutoBreadcrumbs(true)
+ assertTrue(sentryOptions.isEnableAnrWarningBreadcrumbs)
+ }
+
@Test
fun `system event breadcrumbs extras disabled by default`() {
val sentryOptions = SentryAndroidOptions()
diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt
index 4e3c244bd34..6f6dbdeda10 100644
--- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt
+++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt
@@ -498,7 +498,7 @@ class SentryAndroidTest {
fixture.initSut(context = mock()) { options ->
optionsRef = options
options.dsn = "https://key@sentry.io/123"
- assertEquals(20, options.integrations.size)
+ assertEquals(21, options.integrations.size)
options.integrations.removeAll {
it is UncaughtExceptionHandlerIntegration ||
it is ShutdownHookIntegration ||
@@ -508,6 +508,7 @@ class SentryAndroidTest {
it is AppLifecycleIntegration ||
it is AnrIntegration ||
it is AnrProfilingIntegration ||
+ it is AnrWarningListenerIntegration ||
it is ActivityLifecycleIntegration ||
it is ActivityBreadcrumbsIntegration ||
it is UserInteractionIntegration ||
diff --git a/sentry-android-core/src/test/resources/robolectric.properties b/sentry-android-core/src/test/resources/robolectric.properties
index c216eeab9dc..c0f2ddf599d 100644
--- a/sentry-android-core/src/test/resources/robolectric.properties
+++ b/sentry-android-core/src/test/resources/robolectric.properties
@@ -1,2 +1,2 @@
-sdk=21
+sdk=23
application=io.sentry.android.core.ApplicationStub
diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AnrWarningBreadcrumbTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AnrWarningBreadcrumbTest.kt
new file mode 100644
index 00000000000..71da98b2411
--- /dev/null
+++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AnrWarningBreadcrumbTest.kt
@@ -0,0 +1,85 @@
+package io.sentry.uitest.android
+
+import android.content.Intent
+import android.os.Build
+import androidx.test.core.app.launchActivity
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import io.sentry.Breadcrumb
+import io.sentry.SentryOptions
+import io.sentry.android.core.SentryAndroidOptions
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicReference
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class AnrWarningBreadcrumbTest : BaseUiTest() {
+ @AfterTest
+ fun resetTimeout() {
+ runCommand("device_config delete activity_manager $TIMEOUT_KEY")
+ }
+
+ @Test
+ fun anrWarningIsRecordedAsBreadcrumb() {
+ assumeTrue(
+ "ActivityManager.registerAnrWarningListener needs API 37",
+ Build.VERSION.SDK_INT >= 37,
+ )
+
+ // The grace period for calling startForeground() is device-tunable, so shrink it to keep the
+ // test
+ // fast. The warning lands at half of whatever this is set to.
+ runCommand("device_config put activity_manager $TIMEOUT_KEY $TIMEOUT_MS")
+
+ // beforeBreadcrumb sees the breadcrumb on the thread that records it, so there is no need to
+ // capture an event and round-trip it through the relay just to assert on it.
+ val recorded = CountDownLatch(1)
+ val anrBreadcrumb = AtomicReference()
+ initSentry { options: SentryAndroidOptions ->
+ options.isEnableAnrWarningBreadcrumbs = true
+ options.beforeBreadcrumb = SentryOptions.BeforeBreadcrumbCallback { breadcrumb, _ ->
+ if (breadcrumb.category == "app.anr") {
+ anrBreadcrumb.set(breadcrumb)
+ recorded.countDown()
+ }
+ breadcrumb
+ }
+ }
+
+ // startForegroundService is only allowed from the foreground.
+ launchActivity()
+
+ // SlowStartService never calls startForeground(). It waits past the warning at 50% of the grace
+ // period, then stops itself before the 100% deadline, where the system would otherwise throw
+ // ForegroundServiceDidNotStartInTimeException. The main thread stays responsive throughout.
+ context.startForegroundService(
+ Intent(context, SlowStartService::class.java)
+ .putExtra(SlowStartService.EXTRA_STOP_SELF_AFTER_MILLIS, STOP_SELF_AFTER_MS),
+ )
+
+ val arrived = recorded.await(10, TimeUnit.SECONDS)
+ assertTrue(arrived, "No ANR warning within 10s")
+
+ val breadcrumb = anrBreadcrumb.get()
+ assertNotNull(breadcrumb)
+ assertEquals("system", breadcrumb.type)
+ assertEquals("app.anr", breadcrumb.category)
+ assertEquals("ANR warning", breadcrumb.message)
+ assertEquals("start_foreground_service", breadcrumb.getData("anr_type"))
+ assertNotNull(breadcrumb.getData("anr_id"))
+ assertNotNull(breadcrumb.getData("consumed_ms"))
+ }
+
+ private companion object {
+ const val TIMEOUT_KEY = "service_start_foreground_timeout_ms"
+ const val TIMEOUT_MS = 4_000
+ // Comfortably after the warning at 50% of TIMEOUT_MS, comfortably before the deadline at 100%.
+ const val STOP_SELF_AFTER_MS = 2_800L
+ }
+}
diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/BaseUiTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/BaseUiTest.kt
index 529d840b3d3..2415683a14c 100644
--- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/BaseUiTest.kt
+++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/BaseUiTest.kt
@@ -50,7 +50,7 @@ abstract class BaseUiTest {
/** Mock relay server that receives all envelopes sent during the test. */
protected val relay = MockRelay(false, relayIdlingResource)
- private fun runCommand(cmd: String) {
+ protected fun runCommand(cmd: String) {
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
val pfd = automation.executeShellCommand(cmd)
try {
diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml b/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml
index 1b7f8f0108f..86e4d8b0160 100644
--- a/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml
+++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml
@@ -3,6 +3,7 @@
xmlns:tools="http://schemas.android.com/tools">
+
+
diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/SlowStartService.kt b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/SlowStartService.kt
new file mode 100644
index 00000000000..3c4829c5ed1
--- /dev/null
+++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/SlowStartService.kt
@@ -0,0 +1,29 @@
+package io.sentry.uitest.android
+
+import android.app.Service
+import android.content.Intent
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+
+/**
+ * Starts as a foreground service but never calls [startForeground], so the system emits an ANR
+ * warning at half of the `service_start_foreground_timeout_ms` grace period. It then stops itself
+ * before the grace period expires, because at 100% the system throws
+ * ForegroundServiceDidNotStartInTimeException and kills the app.
+ *
+ * Used by `AnrWarningBreadcrumbTest` to provoke an ANR warning without stalling the main thread.
+ */
+class SlowStartService : Service() {
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val stopSelfAfterMillis = intent?.getLongExtra(EXTRA_STOP_SELF_AFTER_MILLIS, 0L) ?: 0L
+ Handler(Looper.getMainLooper()).postDelayed({ stopSelf() }, stopSelfAfterMillis)
+ return START_NOT_STICKY
+ }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ companion object {
+ const val EXTRA_STOP_SELF_AFTER_MILLIS = "stop_self_after_millis"
+ }
+}