sentry-android-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Android SDK
All Skills > SDK Setup > Android SDK
Sentry Android SDK
Sentry Android SDK
Opinionated wizard that scans your Android project and guides you through complete Sentry setup — error monitoring, tracing, profiling, session replay, logging, and more.
这个定制化向导会扫描你的Android项目,引导你完成Sentry的全量配置,包括错误监控、链路追踪、性能剖析、会话回放、日志等功能。
Invoke This Skill When
适用调用场景
- User asks to "add Sentry to Android" or "set up Sentry" in an Android app
- User wants error monitoring, crash reporting, ANR detection, tracing, profiling, session replay, or logging in Android
- User mentions ,
sentry-android, mobile crash tracking, or Sentry for Kotlin/Java Androidio.sentry:sentry-android - User wants to monitor native (NDK) crashes, application not responding (ANR) events, or app startup performance
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (, Gradle pluginio.sentry:sentry-android:8.33.0). Always verify against docs.sentry.io/platforms/android/ before implementing.6.1.0
- 用户要求在Android应用中「添加Sentry」或者「配置Sentry」
- 用户需要为Android应用配置错误监控、崩溃上报、ANR检测、链路追踪、性能剖析、会话回放或日志功能
- 用户提到、
sentry-android、移动端崩溃追踪,或面向Kotlin/Java Android的Sentry相关内容io.sentry:sentry-android - 用户想要监控原生(NDK)崩溃、应用无响应(ANR)事件或应用启动性能
注意: 下文提到的SDK版本和API对应编写时的官方Sentry文档版本(,Gradle插件版本io.sentry:sentry-android:8.33.0)。 实施前请务必对照docs.sentry.io/platforms/android/确认最新内容。6.1.0
Phase 1: Detect
阶段1:项目探测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何推荐方案前,请先运行以下命令了解项目结构:
bash
undefinedDetect project structure and build system
探测项目结构和构建系统
ls build.gradle build.gradle.kts settings.gradle settings.gradle.kts 2>/dev/null
ls build.gradle build.gradle.kts settings.gradle settings.gradle.kts 2>/dev/null
Check AGP version and existing Sentry
检查AGP版本和已有的Sentry配置
grep -r '"com.android.application"' build.gradle* app/build.gradle* 2>/dev/null | head -3
grep -ri sentry build.gradle* app/build.gradle* 2>/dev/null | head -10
grep -r '"com.android.application"' build.gradle* app/build.gradle* 2>/dev/null | head -3
grep -ri sentry build.gradle* app/build.gradle* 2>/dev/null | head -10
Check app-level build file (Groovy vs KTS)
检查应用级构建文件类型(Groovy还是KTS)
ls app/build.gradle app/build.gradle.kts 2>/dev/null
ls app/build.gradle app/build.gradle.kts 2>/dev/null
Detect Kotlin vs Java
探测是Kotlin还是Java项目
find app/src/main -name ".kt" 2>/dev/null | head -3
find app/src/main -name ".java" 2>/dev/null | head -3
find app/src/main -name ".kt" 2>/dev/null | head -3
find app/src/main -name ".java" 2>/dev/null | head -3
Check minSdk, targetSdk
检查minSdk、targetSdk版本
grep -E 'minSdk|targetSdk|compileSdk|minSdkVersion|targetSdkVersion' app/build.gradle app/build.gradle.kts 2>/dev/null | head -6
grep -E 'minSdk|targetSdk|compileSdk|minSdkVersion|targetSdkVersion' app/build.gradle app/build.gradle.kts 2>/dev/null | head -6
Detect Jetpack Compose
探测是否使用Jetpack Compose
grep -E 'compose|androidx.compose' app/build.gradle app/build.gradle.kts 2>/dev/null | head -5
grep -E 'compose|androidx.compose' app/build.gradle app/build.gradle.kts 2>/dev/null | head -5
Detect OkHttp (popular HTTP client — has dedicated integration)
探测是否使用OkHttp(流行HTTP客户端,有专属集成方案)
grep -E 'okhttp|retrofit' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'okhttp|retrofit' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
Detect Room or SQLite
探测是否使用Room或SQLite
grep -E 'androidx.room|androidx.sqlite' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'androidx.room|androidx.sqlite' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
Detect Timber (logging library)
探测是否使用Timber(日志库)
grep -E 'timber' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'timber' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
Detect Jetpack Navigation
探测是否使用Jetpack Navigation
grep -E 'androidx.navigation' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'androidx.navigation' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
Detect Apollo (GraphQL)
探测是否使用Apollo(GraphQL)
grep -E 'apollo' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'apollo' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
Check existing Sentry initialization
检查已有的Sentry初始化代码
grep -r "SentryAndroid.init|io.sentry.Sentry" app/src/ 2>/dev/null | head -5
grep -r "SentryAndroid.init\|io.sentry.Sentry" app/src/ 2>/dev/null | head -5
Check Application class
检查Application类
find app/src/main -name ".kt" -o -name ".java" 2>/dev/null | xargs grep -l "Application()" 2>/dev/null | head -3
find app/src/main -name ".kt" -o -name ".java" 2>/dev/null | xargs grep -l "Application()" 2>/dev/null | head -3
Adjacent backend (for cross-linking)
相邻后端项目(用于跨端链路关联)
ls ../backend ../server ../api 2>/dev/null
find .. -maxdepth 2 ( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" ) 2>/dev/null | grep -v node_modules | head -5
**What to determine:**
| Question | Impact |
|----------|--------|
| `build.gradle.kts` present? | Use Kotlin DSL syntax in all examples |
| `minSdk < 26`? | Note Session Replay requires API 26+ — silent no-op below that |
| Compose detected? | Recommend `sentry-compose-android` and Compose-specific masking |
| OkHttp present? | Recommend `sentry-okhttp` interceptor or Gradle plugin bytecode auto-instrumentation |
| Room/SQLite present? | Recommend `sentry-android-sqlite` or plugin bytecode instrumentation |
| Timber present? | Recommend `sentry-android-timber` integration |
| Jetpack Navigation? | Recommend `sentry-android-navigation` for screen tracking |
| Already has `SentryAndroid.init()`? | Skip install, jump to feature config |
| Application subclass exists? | That's where `SentryAndroid.init()` goes |
---ls ../backend ../server ../api 2>/dev/null
find .. -maxdepth 2 \( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" \) 2>/dev/null | grep -v node_modules | head -5
**需要确认的信息:**
| 问题 | 影响 |
|----------|--------|
| 是否存在`build.gradle.kts`? | 所有示例使用Kotlin DSL语法 |
| `minSdk < 26`? | 说明会话回放仅支持API 26+,低于该版本会静默不生效 |
| 是否检测到Compose? | 推荐使用`sentry-compose-android`和Compose专属隐私屏蔽功能 |
| 是否存在OkHttp? | 推荐使用`sentry-okhttp`拦截器或Gradle插件字节码自动插桩 |
| 是否存在Room/SQLite? | 推荐使用`sentry-android-sqlite`或插件字节码插桩 |
| 是否存在Timber? | 推荐使用`sentry-android-timber`集成 |
| 是否使用Jetpack Navigation? | 推荐使用`sentry-android-navigation`做页面追踪 |
| 已存在`SentryAndroid.init()`代码? | 跳过安装步骤,直接进入功能配置阶段 |
| 是否存在Application子类? | `SentryAndroid.init()`需要放在该类中 |
---Phase 2: Recommend
阶段2:方案推荐
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage — always set up these):
- ✅ Error Monitoring — captures uncaught exceptions, ANRs, and native NDK crashes automatically
- ✅ Tracing — auto-instruments Activity lifecycle, app start, HTTP requests, and database queries
- ✅ Session Replay — records screen captures and user interactions for debugging (API 26+)
Optional (enhanced observability):
- ⚡ Profiling — continuous UI profiling (recommended) or transaction-based sampling
- ⚡ Logging — structured logs via , with optional Timber bridge
Sentry.logger() - ⚡ User Feedback — collect user-submitted bug reports from inside the app
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline for any Android app |
| Tracing | Always for Android — app start time, Activity lifecycle, network latency matter |
| Session Replay | User-facing production app on API 26+; visual debugging of user issues |
| Profiling | Performance-sensitive apps, startup time investigations, production perf analysis |
| Logging | App uses structured logging or you want log-to-trace correlation in Sentry |
| User Feedback | Beta or customer-facing app where you want user-submitted bug reports |
Propose: "For your [Kotlin / Java] Android app (minSdk X), I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Profiling and Logging?"
基于探测到的信息给出具体的推荐方案,不要问开放性问题,直接给出提案:
推荐基础配置(所有场景都建议配置):
- ✅ 错误监控 — 自动捕获未捕获异常、ANR和原生NDK崩溃
- ✅ 链路追踪 — 自动插桩Activity生命周期、应用启动、HTTP请求和数据库查询
- ✅ 会话回放 — 录屏和用户交互记录,用于问题调试(仅支持API 26+)
可选增强配置(提升可观测性):
- ⚡ 性能剖析 — 持续UI性能剖析(推荐)或基于事务的采样剖析
- ⚡ 日志 — 通过输出结构化日志,可选支持Timber桥接
Sentry.logger() - ⚡ 用户反馈 — 收集应用内用户提交的bug报告
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 所有场景必选 — 任何Android应用的基础能力 |
| 链路追踪 | Android项目必选 — 用于分析应用启动时间、Activity生命周期、网络延迟 |
| 会话回放 | 面向用户的生产环境应用且minSdk≥26;需要可视化复现用户问题的场景 |
| 性能剖析 | 对性能敏感的应用、启动时间优化、生产环境性能分析场景 |
| 日志 | 应用使用结构化日志,或者需要在Sentry中实现日志与链路关联的场景 |
| 用户反馈 | 测试版或面向用户的应用,需要收集用户提交的bug报告的场景 |
提案示例:"针对你的[Kotlin / Java] Android应用(minSdk X),我推荐配置错误监控+链路追踪+会话回放。是否需要同时添加性能剖析和日志功能?"
Phase 3: Guide
阶段3:安装引导
Determine Your Setup Path
选择安装路径
| Project type | Recommended setup | Complexity |
|---|---|---|
| New project, no existing Sentry | Gradle plugin (recommended) | Low — plugin handles most config |
| Existing project, no Sentry | Gradle plugin or manual init | Medium — add dependency + Application class |
| Manual full control | | Medium — explicit config, most flexible |
| 项目类型 | 推荐安装方式 | 复杂度 |
|---|---|---|
| 新项目,无已有Sentry配置 | Gradle插件(推荐) | 低 — 插件会处理大部分配置 |
| 现有项目,无Sentry配置 | Gradle插件或手动初始化 | 中 — 添加依赖+在Application类初始化 |
| 需要完全手动控制配置 | 在Application中调用 | 中 — 配置明确,灵活性最高 |
Option 1: Wizard (Recommended)
选项1:向导安装(推荐)
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:npx @sentry/wizard@latest -i androidIt handles login, org/project selection, Gradle plugin setup, dependency installation, DSN configuration, and ProGuard/R8 mapping upload.Once it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
需要你自行运行 — 向导会打开浏览器完成登录,需要交互输入,Agent无法自动处理。 复制以下命令到终端运行:npx @sentry/wizard@latest -i android它会自动处理登录、组织/项目选择、Gradle插件配置、依赖安装、DSN配置和ProGuard/R8映射文件上传。运行完成后回到本页面,直接跳转到验证环节即可。
如果用户跳过向导,请继续使用下方选项2(手动安装)。
Option 2: Manual Setup
选项2:手动安装
Path A: Gradle Plugin (Recommended)
路径A:使用Gradle插件(推荐)
The Sentry Gradle plugin is the easiest setup path. It:
- Uploads ProGuard/R8 mapping files automatically on release builds
- Injects source context into stack frames
- Optionally instruments OkHttp, Room/SQLite, File I/O, Compose navigation, and via bytecode transforms (zero source changes)
android.util.Log
Step 1 — Add the plugin to (project-level)
build.gradle[.kts]Groovy DSL ():
build.gradlegroovy
plugins {
id "io.sentry.android.gradle" version "6.1.0" apply false
}Kotlin DSL ():
build.gradle.ktskotlin
plugins {
id("io.sentry.android.gradle") version "6.1.0" apply false
}Step 2 — Apply plugin + add dependencies in
app/build.gradle[.kts]Groovy DSL:
groovy
plugins {
id "com.android.application"
id "io.sentry.android.gradle"
}
android {
// ...
}
dependencies {
// Use BOM for consistent versions across sentry modules
implementation platform("io.sentry:sentry-bom:8.33.0")
implementation "io.sentry:sentry-android"
// Optional integrations (add what's relevant):
// implementation "io.sentry:sentry-android-timber" // Timber bridge
// implementation "io.sentry:sentry-android-fragment" // Fragment lifecycle tracing
// implementation "io.sentry:sentry-compose-android" // Jetpack Compose support
// implementation "io.sentry:sentry-android-navigation" // Jetpack Navigation
// implementation "io.sentry:sentry-okhttp" // OkHttp interceptor
// implementation "io.sentry:sentry-android-sqlite" // Room/SQLite tracing
// implementation "io.sentry:sentry-kotlin-extensions" // Coroutine context propagation
}
sentry {
org = "YOUR_ORG_SLUG"
projectName = "YOUR_PROJECT_SLUG"
authToken = System.getenv("SENTRY_AUTH_TOKEN")
// Enable auto-instrumentation via bytecode transforms (no source changes needed)
tracingInstrumentation {
enabled = true
features = [InstrumentationFeature.DATABASE, InstrumentationFeature.FILE_IO,
InstrumentationFeature.OKHTTP, InstrumentationFeature.COMPOSE]
}
// Upload ProGuard mapping and source context on release
autoUploadProguardMapping = true
includeSourceContext = true
}Kotlin DSL ():
app/build.gradle.ktskotlin
plugins {
id("com.android.application")
id("io.sentry.android.gradle")
}
dependencies {
implementation(platform("io.sentry:sentry-bom:8.33.0"))
implementation("io.sentry:sentry-android")
// Optional integrations:
// implementation("io.sentry:sentry-android-timber")
// implementation("io.sentry:sentry-android-fragment")
// implementation("io.sentry:sentry-compose-android")
// implementation("io.sentry:sentry-android-navigation")
// implementation("io.sentry:sentry-okhttp")
// implementation("io.sentry:sentry-android-sqlite")
// implementation("io.sentry:sentry-kotlin-extensions")
}
sentry {
org = "YOUR_ORG_SLUG"
projectName = "YOUR_PROJECT_SLUG"
authToken = System.getenv("SENTRY_AUTH_TOKEN")
tracingInstrumentation {
enabled = true
features = setOf(
InstrumentationFeature.DATABASE,
InstrumentationFeature.FILE_IO,
InstrumentationFeature.OKHTTP,
InstrumentationFeature.COMPOSE,
)
}
autoUploadProguardMapping = true
includeSourceContext = true
}Step 3 — Initialize Sentry in your Application class
If you don't have an Application subclass, create one:
kotlin
// MyApplication.kt
import android.app.Application
import io.sentry.SentryLevel
import io.sentry.android.core.SentryAndroid
import io.sentry.android.replay.SentryReplayOptions
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
SentryAndroid.init(this) { options ->
options.dsn = "YOUR_SENTRY_DSN"
// Tracing — lower to 0.1–0.2 in high-traffic production
options.tracesSampleRate = 1.0
// Profiling — use continuous UI profiling (recommended, SDK ≥ 8.7.0)
options.profileSessionSampleRate = 1.0
// Session Replay (API 26+ only; silent no-op below API 26)
options.sessionReplay.sessionSampleRate = 0.1 // 10% of all sessions
options.sessionReplay.onErrorSampleRate = 1.0 // 100% on error
// Structured logging
options.logs.isEnabled = true
// Environment
options.environment = BuildConfig.BUILD_TYPE
}
}
}Java equivalent:
java
// MyApplication.java
import android.app.Application;
import io.sentry.android.core.SentryAndroid;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SentryAndroid.init(this, options -> {
options.setDsn("YOUR_SENTRY_DSN");
options.setTracesSampleRate(1.0);
options.setProfileSessionSampleRate(1.0);
options.getSessionReplay().setSessionSampleRate(0.1);
options.getSessionReplay().setOnErrorSampleRate(1.0);
options.getLogs().setEnabled(true);
options.setEnvironment(BuildConfig.BUILD_TYPE);
});
}
}Step 4 — Register Application in
AndroidManifest.xmlxml
<application
android:name=".MyApplication"
... >Sentry Gradle插件是最简单的安装方案,它可以:
- 发布构建时自动上传ProGuard/R8映射文件
- 向堆栈帧注入源码上下文
- 可选通过字节码转换实现OkHttp、Room/SQLite、文件I/O、Compose导航、的自动插桩(无需修改源码)
android.util.Log
步骤1 — 在项目级中添加插件
build.gradle[.kts]Groovy DSL ():
build.gradlegroovy
plugins {
id "io.sentry.android.gradle" version "6.1.0" apply false
}Kotlin DSL ():
build.gradle.ktskotlin
plugins {
id("io.sentry.android.gradle") version "6.1.0" apply false
}步骤2 — 在中应用插件并添加依赖
app/build.gradle[.kts]Groovy DSL:
groovy
plugins {
id "com.android.application"
id "io.sentry.android.gradle"
}
android {
// ...
}
dependencies {
// 使用BOM保证所有sentry模块版本一致
implementation platform("io.sentry:sentry-bom:8.33.0")
implementation "io.sentry:sentry-android"
// 可选集成(按需添加):
// implementation "io.sentry:sentry-android-timber" // Timber桥接
// implementation "io.sentry:sentry-android-fragment" // Fragment生命周期追踪
// implementation "io.sentry:sentry-compose-android" // Jetpack Compose支持
// implementation "io.sentry:sentry-android-navigation" // Jetpack Navigation支持
// implementation "io.sentry:sentry-okhttp" // OkHttp拦截器
// implementation "io.sentry:sentry-android-sqlite" // Room/SQLite追踪
// implementation "io.sentry:sentry-kotlin-extensions" // 协程上下文传播
}
sentry {
org = "YOUR_ORG_SLUG"
projectName = "YOUR_PROJECT_SLUG"
authToken = System.getenv("SENTRY_AUTH_TOKEN")
// 启用字节码转换自动插桩(无需修改源码)
tracingInstrumentation {
enabled = true
features = [InstrumentationFeature.DATABASE, InstrumentationFeature.FILE_IO,
InstrumentationFeature.OKHTTP, InstrumentationFeature.COMPOSE]
}
// 发布时自动上传ProGuard映射和源码上下文
autoUploadProguardMapping = true
includeSourceContext = true
}Kotlin DSL ():
app/build.gradle.ktskotlin
plugins {
id("com.android.application")
id("io.sentry.android.gradle")
}
dependencies {
implementation(platform("io.sentry:sentry-bom:8.33.0"))
implementation("io.sentry:sentry-android")
// 可选集成:
// implementation("io.sentry:sentry-android-timber")
// implementation("io.sentry:sentry-android-fragment")
// implementation("io.sentry:sentry-compose-android")
// implementation("io.sentry:sentry-android-navigation")
// implementation("io.sentry:sentry-okhttp")
// implementation("io.sentry:sentry-android-sqlite")
// implementation("io.sentry:sentry-kotlin-extensions")
}
sentry {
org = "YOUR_ORG_SLUG"
projectName = "YOUR_PROJECT_SLUG"
authToken = System.getenv("SENTRY_AUTH_TOKEN")
tracingInstrumentation {
enabled = true
features = setOf(
InstrumentationFeature.DATABASE,
InstrumentationFeature.FILE_IO,
InstrumentationFeature.OKHTTP,
InstrumentationFeature.COMPOSE,
)
}
autoUploadProguardMapping = true
includeSourceContext = true
}步骤3 — 在Application类中初始化Sentry
如果你还没有Application子类,请先创建一个:
kotlin
// MyApplication.kt
import android.app.Application
import io.sentry.SentryLevel
import io.sentry.android.core.SentryAndroid
import io.sentry.android.replay.SentryReplayOptions
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
SentryAndroid.init(this) { options ->
options.dsn = "YOUR_SENTRY_DSN"
// 链路追踪 — 高流量生产环境建议调低到0.1–0.2
options.tracesSampleRate = 1.0
// 性能剖析 — 使用持续UI剖析(推荐,SDK ≥ 8.7.0支持)
options.profileSessionSampleRate = 1.0
// 会话回放(仅支持API 26+;低于该版本会静默不生效)
options.sessionReplay.sessionSampleRate = 0.1 // 录制10%的全量会话
options.sessionReplay.onErrorSampleRate = 1.0 // 异常会话100%录制
// 结构化日志
options.logs.isEnabled = true
// 环境标识
options.environment = BuildConfig.BUILD_TYPE
}
}
}Java版本等效代码:
java
// MyApplication.java
import android.app.Application;
import io.sentry.android.core.SentryAndroid;
public class MyApplication : Application {
@Override
public void onCreate() {
super.onCreate();
SentryAndroid.init(this, options -> {
options.setDsn("YOUR_SENTRY_DSN");
options.setTracesSampleRate(1.0);
options.setProfileSessionSampleRate(1.0);
options.getSessionReplay().setSessionSampleRate(0.1);
options.getSessionReplay().setOnErrorSampleRate(1.0);
options.getLogs().setEnabled(true);
options.setEnvironment(BuildConfig.BUILD_TYPE);
});
}
}步骤4 — 在中注册Application
AndroidManifest.xmlxml
<application
android:name=".MyApplication"
... >Path B: Manual Setup (No Gradle Plugin)
路径B:手动安装(不使用Gradle插件)
Use this if you can't use the Gradle plugin (e.g., non-standard build setups).
Step 1 — Add dependency in
app/build.gradle[.kts]kotlin
dependencies {
implementation(platform("io.sentry:sentry-bom:8.33.0"))
implementation("io.sentry:sentry-android")
}Step 2 — Initialize in Application class (same as Path A, Step 3)
Step 3 — Configure ProGuard/R8 manually
The Sentry SDK ships a ProGuard rules file automatically. For manual mapping upload, install and add to your CI:
sentry-clibash
sentry-cli releases files "my-app@1.0.0+42" upload-proguard \
--org YOUR_ORG --project YOUR_PROJECT \
app/build/outputs/mapping/release/mapping.txt如果你无法使用Gradle插件(比如非标准构建配置)可以使用此方案。
步骤1 — 在中添加依赖
app/build.gradle[.kts]kotlin
dependencies {
implementation(platform("io.sentry:sentry-bom:8.33.0"))
implementation("io.sentry:sentry-android")
}步骤2 — 在Application类中初始化(和路径A步骤3完全一致)
步骤3 — 手动配置ProGuard/R8
Sentry SDK会自动附带ProGuard规则文件。如果需要手动上传映射文件,请安装并添加到你的CI流程中:
sentry-clibash
sentry-cli releases files "my-app@1.0.0+42" upload-proguard \\
--org YOUR_ORG --project YOUR_PROJECT \\
app/build/outputs/mapping/release/mapping.txtQuick Reference: Full-Featured SentryAndroid.init()
SentryAndroid.init()快速参考:全功能SentryAndroid.init()
配置
SentryAndroid.init()kotlin
SentryAndroid.init(this) { options ->
options.dsn = "YOUR_SENTRY_DSN"
// Environment and release
options.environment = BuildConfig.BUILD_TYPE // "debug", "release", etc.
options.release = "${BuildConfig.APPLICATION_ID}@${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}"
// Tracing — sample 100% in dev, lower to 10–20% in production
options.tracesSampleRate = 1.0
// Continuous UI profiling (recommended over transaction-based)
options.profileSessionSampleRate = 1.0
// Session Replay (API 26+; silent no-op on API 21–25)
options.sessionReplay.sessionSampleRate = 0.1
options.sessionReplay.onErrorSampleRate = 1.0
options.sessionReplay.maskAllText = true // mask text for privacy
options.sessionReplay.maskAllImages = true // mask images for privacy
// Structured logging
options.logs.isEnabled = true
// Error enrichment
options.isAttachScreenshot = true // capture screenshot on error
options.isAttachViewHierarchy = true // attach view hierarchy JSON
// ANR detection (5s default; watchdog + ApplicationExitInfo API 30+)
options.isAnrEnabled = true
// NDK native crash handling (enabled by default)
options.isEnableNdk = true
// Send PII: IP address, user data
options.sendDefaultPii = true
// Trace propagation (backend distributed tracing)
options.tracePropagationTargets = listOf("api.yourapp.com", ".*\\.yourapp\\.com")
// Verbose logging — disable in production
options.isDebug = BuildConfig.DEBUG
}kotlin
SentryAndroid.init(this) { options ->
options.dsn = "YOUR_SENTRY_DSN"
// 环境和版本标识
options.environment = BuildConfig.BUILD_TYPE // 如"debug", "release"等
options.release = "${BuildConfig.APPLICATION_ID}@${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}"
// 链路追踪 — 开发环境采样100%,生产环境建议调低到10–20%
options.tracesSampleRate = 1.0
// 持续UI性能剖析(比基于事务的剖析更推荐)
options.profileSessionSampleRate = 1.0
// 会话回放(仅API 26+支持;API 21–25会静默不生效)
options.sessionReplay.sessionSampleRate = 0.1
options.sessionReplay.onErrorSampleRate = 1.0
options.sessionReplay.maskAllText = true // 隐私保护:屏蔽所有文本
options.sessionReplay.maskAllImages = true // 隐私保护:屏蔽所有图片
// 结构化日志
options.logs.isEnabled = true
// 错误信息增强
options.isAttachScreenshot = true // 异常时捕获截图
options.isAttachViewHierarchy = true // 附加视图层级JSON
// ANR检测(默认5s超时;使用看门狗+API 30+的ApplicationExitInfo API)
options.isAnrEnabled = true
// NDK原生崩溃处理(默认启用)
options.isEnableNdk = true
// 发送PII信息:IP地址、用户数据
options.sendDefaultPii = true
// 链路传播(后端分布式追踪)
options.tracePropagationTargets = listOf("api.yourapp.com", ".*\\\\.yourapp\\\\.com")
// 详细日志 — 生产环境请禁用
options.isDebug = BuildConfig.DEBUG
}For Each Agreed Feature
针对每个确认开启的功能
Walk through features one at a time. Load the reference file for each, follow its steps, then verify before moving on:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing & Performance | | Always for Android (Activity lifecycle, network) |
| Profiling | | Performance-sensitive production apps |
| Session Replay | | User-facing apps (API 26+) |
| Logging | | Structured logging / log-to-trace correlation |
| Metrics | | Custom metric tracking (Beta, SDK ≥ 8.30.0) |
| Crons | | Scheduled jobs, WorkManager check-ins |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个功能完成配置,加载对应参考文件,按步骤操作,验证通过后再进入下一个功能:
| 功能 | 参考文件路径 | 加载场景 |
|---|---|---|
| 错误监控 | | 所有场景必选(基础能力) |
| 链路追踪与性能 | | Android项目必选(Activity生命周期、网络分析) |
| 性能剖析 | | 对性能敏感的生产应用 |
| 会话回放 | | 面向用户的应用(API 26+) |
| 日志 | | 结构化日志/需要日志与链路关联的场景 |
| 指标 | | 自定义指标追踪(Beta功能,SDK ≥ 8.30.0支持) |
| 定时任务监控 | | 定时任务、WorkManager心跳检测场景 |
每个功能的操作流程:,严格按照步骤操作,验证生效后再继续。
读取${SKILL_ROOT}/references/<feature>.mdIntegration Reference
集成参考
Built-in (Auto-Enabled)
内置集成(自动启用)
These integrations activate automatically when is called:
SentryAndroid.init()| Integration | What it does |
|---|---|
| Captures all uncaught Java/Kotlin exceptions |
| ANR detection via watchdog thread (5s) + ApplicationExitInfo (API 30+) |
| Native (C/C++) crash capture via |
| Auto-instruments Activity create/resume/pause for TTID/TTFD |
| Measures cold/warm/hot app start time |
| Records connectivity changes as breadcrumbs |
| Records battery, screen on/off, etc. |
| Records foreground/background transitions |
| Breadcrumbs for taps, swipes, input events |
| Tracks active Activity for context |
调用后这些集成会自动激活:
SentryAndroid.init()| 集成 | 功能 |
|---|---|
| 捕获所有未捕获的Java/Kotlin异常 |
| 通过看门狗线程(5s超时)+ ApplicationExitInfo(API 30+)检测ANR |
| 通过 |
| 自动插桩Activity的create/resume/pause生命周期,统计TTID/TTFD |
| 统计冷启动/温启动/热启动耗时 |
| 记录网络连接变化作为用户行为面包屑 |
| 记录电池、屏幕亮灭等系统事件作为面包屑 |
| 记录应用前后台切换事件 |
| 记录点击、滑动、输入等用户交互作为面包屑 |
| 追踪当前活跃Activity作为上下文 |
Optional Integrations
可选集成
Add the artifact to your block (versions managed by BOM):
dependencies {}| Integration | Artifact | When to add |
|---|---|---|
| Timber | | App uses Timber for logging |
| Fragment | | App uses Jetpack Fragments (lifecycle tracing) |
| Compose | | App uses Jetpack Compose (navigation + masking) |
| Navigation | | App uses Jetpack Navigation Component |
| OkHttp | | App uses OkHttp or Retrofit |
| Room/SQLite | | App uses Room or raw SQLite |
| Apollo 3 | | App uses Apollo GraphQL v3 |
| Apollo 4 | | App uses Apollo GraphQL v4 |
| Kotlin Extensions | | Kotlin coroutines context propagation |
| Ktor Client | | App uses Ktor HTTP client |
| LaunchDarkly | | App uses LaunchDarkly feature flags |
将对应的依赖添加到块(版本由BOM统一管理):
dependencies {}| 集成 | 依赖坐标 | 添加场景 |
|---|---|---|
| Timber | | 应用使用Timber做日志打印 |
| Fragment | | 应用使用Jetpack Fragments(生命周期追踪) |
| Compose | | 应用使用Jetpack Compose(导航+隐私屏蔽) |
| Navigation | | 应用使用Jetpack Navigation组件 |
| OkHttp | | 应用使用OkHttp或Retrofit |
| Room/SQLite | | 应用使用Room或原生SQLite |
| Apollo 3 | | 应用使用Apollo GraphQL v3 |
| Apollo 4 | | 应用使用Apollo GraphQL v4 |
| Kotlin扩展 | | Kotlin协程上下文传播 |
| Ktor Client | | 应用使用Ktor HTTP客户端 |
| LaunchDarkly | | 应用使用LaunchDarkly feature flag |
Gradle Plugin Bytecode Instrumentation
Gradle插件字节码插桩
The plugin can inject instrumentation automatically (no source changes):
| Feature | Instruments | Enable via |
|---|---|---|
| Room DAO, SupportSQLiteOpenHelper | |
| FileInputStream, FileOutputStream | |
| OkHttpClient.Builder automatically | |
| NavHostController auto-instrumentation | |
| | |
插件可以自动注入插桩逻辑(无需修改源码):
| 功能 | 插桩对象 | 启用方式 |
|---|---|---|
| Room DAO、SupportSQLiteOpenHelper | 通过 |
| FileInputStream、FileOutputStream | 通过 |
| OkHttpClient.Builder自动插桩 | 通过 |
| NavHostController自动插桩 | 通过 |
| 捕获 | 通过 |
Configuration Reference
配置参考
Core SentryOptions
(via SentryAndroid.init
)
SentryOptionsSentryAndroid.init核心SentryOptions
(通过SentryAndroid.init
配置)
SentryOptionsSentryAndroid.init| Option | Type | Default | Purpose |
|---|---|---|---|
| | — | Required. Project DSN; SDK silently disabled if empty |
| | — | e.g., |
| | — | App version, e.g., |
| | — | Build variant / distribution identifier |
| | | Include PII: IP address, user data |
| | | Error event sampling (0.0–1.0) |
| | | Max breadcrumbs per event |
| | | Auto-attach stack traces to message events |
| | | Capture screenshot on error |
| | | Attach JSON view hierarchy as attachment |
| | | Verbose SDK output. Never use in production |
| | | Disable SDK entirely (e.g., for testing) |
| | — | Modify or drop error events before sending |
| | — | Filter breadcrumbs before storage |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | — | 必填。 项目DSN;为空时SDK会静默禁用 |
| | — | 环境标识,如 |
| | — | 应用版本,如 |
| | — | 构建变体/分发标识 |
| | | 是否包含PII信息:IP地址、用户数据 |
| | | 错误事件采样率(0.0–1.0) |
| | | 每个事件最多携带的面包屑数量 |
| | | 自动为消息事件附加堆栈 |
| | | 异常时捕获截图 |
| | | 附加JSON格式的视图层级作为附件 |
| | | SDK详细日志输出。生产环境绝对不要开启 |
| | | 完全禁用SDK(比如测试场景) |
| | — | 发送错误事件前修改或丢弃事件 |
| | — | 存储面包屑前过滤面包屑 |
Tracing Options
链路追踪配置
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Transaction sample rate (0–1). Use |
| | — | Per-transaction sampling; overrides |
| | | Hosts/URLs to receive |
| | | Auto-instrument Activity lifecycle |
| | | TTFD spans (requires |
| | | Auto-instrument user gestures as transactions |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 事务采样率(0–1)。开发环境建议用 |
| | — | 按事务维度自定义采样,优先级高于 |
| | | 需要接收 |
| | | 自动插桩Activity生命周期 |
| | | TTFD span统计(需要主动调用 |
| | | 自动将用户手势作为事务统计 |
Profiling Options
性能剖析配置
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Continuous profiling sample rate (SDK ≥ 8.7.0, API 22+) |
| | | Legacy transaction profiling rate (mutually exclusive with continuous) |
| | | Auto-start profiling session on app launch |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 持续性能剖析采样率(SDK ≥ 8.7.0支持,API 22+) |
| | | 旧版基于事务的剖析采样率(和持续剖析互斥) |
| | | 应用启动时自动开启剖析会话 |
ANR Options
ANR配置
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Enable ANR watchdog thread |
| | | Milliseconds before reporting ANR |
| | | Report ANRs in debug builds (noisy in debugger) |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 启用ANR看门狗线程 |
| | | ANR上报超时时间(毫秒) |
| | | debug构建下上报ANR(调试器暂停线程时会产生大量误报) |
NDK Options
NDK配置
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Enable native crash capture via sentry-native |
| | | Sync Java scope (user, tags) to NDK layer |
| | | Fetch NDK tombstone files for enrichment |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 通过sentry-native启用原生崩溃捕获 |
| | | 将Java层的scope(用户、标签)同步到NDK层 |
| | | 拉取NDK tombstone文件丰富崩溃信息 |
Session Replay Options (options.sessionReplay
)
options.sessionReplay会话回放配置(options.sessionReplay
下的属性)
options.sessionReplay| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Fraction of all sessions to record |
| | | Fraction of error sessions to record |
| | | Mask all text in replays |
| | | Mask all images in replays |
| | | Video quality: |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 全量会话录制比例 |
| | | 异常会话录制比例 |
| | | 屏蔽回放中的所有文本 |
| | | 屏蔽回放中的所有图片 |
| | | 视频质量: |
Logging Options (options.logs
)
options.logs日志配置(options.logs
下的属性)
options.logs| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Enable |
| | — | Filter/modify log entries before sending |
| 配置项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 启用 |
| | — | 发送日志前过滤/修改日志内容 |
Environment Variables
环境变量
| Variable | Purpose | Notes |
|---|---|---|
| Data Source Name | Set in CI; SDK reads from environment at init |
| Upload ProGuard mappings and source context | Never commit — use CI/CD secrets |
| Organization slug | Used by Gradle plugin |
| Project slug | Used by Gradle plugin |
| Release identifier | Falls back from |
| Environment name | Falls back from |
You can also configure DSN and many options via meta-data:
AndroidManifest.xmlxml
<application>
<meta-data android:name="io.sentry.dsn" android:value="YOUR_DSN" />
<meta-data android:name="io.sentry.traces-sample-rate" android:value="1.0" />
<meta-data android:name="io.sentry.environment" android:value="production" />
<meta-data android:name="io.sentry.anr.enable" android:value="true" />
<meta-data android:name="io.sentry.attach-screenshot" android:value="true" />
<meta-data android:name="io.sentry.attach-view-hierarchy" android:value="true" />
</application>⚠️ Manifest meta-data is a convenient alternative but does not support the full option set. For complex configuration (session replay, profiling, hooks), use.SentryAndroid.init()
| 变量名 | 用途 | 备注 |
|---|---|---|
| 数据源名称 | 在CI中设置;SDK初始化时会从环境变量读取 |
| 上传ProGuard映射和源码上下文的凭证 | 绝对不要提交到代码仓库 — 存放在CI/CD密钥管理中 |
| 组织slug | 供Gradle插件的 |
| 项目slug | 供Gradle插件的 |
| 版本标识 | 优先级低于 |
| 环境标识 | 优先级低于 |
你也可以通过的meta-data配置DSN和很多其他选项:
AndroidManifest.xmlxml
<application>
<meta-data android:name="io.sentry.dsn" android:value="YOUR_DSN" />
<meta-data android:name="io.sentry.traces-sample-rate" android:value="1.0" />
<meta-data android:name="io.sentry.environment" android:value="production" />
<meta-data android:name="io.sentry.anr.enable" android:value="true" />
<meta-data android:name="io.sentry.attach-screenshot" android:value="true" />
<meta-data android:name="io.sentry.attach-view-hierarchy" android:value="true" />
</application>⚠️ Manifest meta-data是很方便的配置方式,但不支持全量配置项。复杂配置(会话回放、性能剖析、钩子函数)请使用。SentryAndroid.init()
Verification
验证
After setup, verify Sentry is receiving events:
Test error capture:
kotlin
// In an Activity or Fragment
try {
throw RuntimeException("Sentry Android SDK test")
} catch (e: Exception) {
Sentry.captureException(e)
}Test tracing:
kotlin
val transaction = Sentry.startTransaction("test-task", "task")
val span = transaction.startChild("test-span", "description")
span.finish()
transaction.finish()Test structured logging (SDK ≥ 8.12.0):
kotlin
Sentry.logger().info("Sentry logging test")
Sentry.logger().error("Error log test", Exception("test error"))Check the Sentry dashboard:
- Issues → your test exception should appear within seconds
- Traces → look for transaction with child span
test-task - Replays → session recording visible after app interaction (requires API 26+)
- Logs → structured log entries visible under Logs tab
If nothing appears:
- Set — SDK logs to Logcat
options.isDebug = true - Verify DSN is correct and matches your Sentry project
- Check that your class is registered in
ApplicationasAndroidManifest.xmlandroid:name - Confirm the device/emulator has internet connectivity
- For NDK crashes, ensure (default) and build with NDK support
isEnableNdk = true
配置完成后,请验证Sentry是否正常接收事件:
测试错误捕获:
kotlin
// 在Activity或Fragment中运行
try {
throw RuntimeException("Sentry Android SDK test")
} catch (e: Exception) {
Sentry.captureException(e)
}测试链路追踪:
kotlin
val transaction = Sentry.startTransaction("test-task", "task")
val span = transaction.startChild("test-span", "description")
span.finish()
transaction.finish()测试结构化日志(SDK ≥ 8.12.0支持):
kotlin
Sentry.logger().info("Sentry logging test")
Sentry.logger().error("Error log test", Exception("test error"))检查Sentry控制台:
- Issues → 几秒内应该可以看到你测试的异常
- Traces → 可以找到带有子span的事务
test-task - Replays → 应用交互后可以看到会话录制(需要API 26+)
- Logs → 结构化日志会展示在Logs标签页下
如果没有收到任何数据:
- 设置— SDK会向Logcat输出日志
options.isDebug = true - 确认DSN正确且和你的Sentry项目匹配
- 检查你的类已经在
Application中通过AndroidManifest.xml注册android:name - 确认设备/模拟器有网络连接
- 针对NDK崩溃,确认(默认开启)且项目配置了NDK支持
isEnableNdk = true
Phase 4: Cross-Link
阶段4:跨端关联
After completing Android setup, check for a backend or web frontend missing Sentry coverage:
bash
undefined完成Android端配置后,检查是否有未配置Sentry的后端或Web前端项目:
bash
undefinedAdjacent backend directories
相邻后端目录
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -5
cat ../Gemfile 2>/dev/null | head -3
ls ../backend/package.json ../server/package.json 2>/dev/null
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -5
cat ../Gemfile 2>/dev/null | head -3
ls ../backend/package.json ../server/package.json 2>/dev/null
iOS counterpart app
对应的iOS应用
ls ../ios ../YourApp-iOS 2>/dev/null
find .. -maxdepth 3 -name "*.xcodeproj" 2>/dev/null | head -3
If a backend or related platform exists without Sentry, suggest the matching skill:
| Detected | Suggest skill |
|----------|--------------|
| Go backend (`go.mod`) | `sentry-go-sdk` |
| Python backend (`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby backend (`Gemfile`) | `sentry-ruby-sdk` |
| Node.js backend | `@sentry/node` — see [docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |
| iOS app (`.xcodeproj`) | `sentry-cocoa-sdk` |
| React Native (`package.json` with `react-native`) | `sentry-react-native-sdk` |
| React / Next.js web | `sentry-react-sdk` or `sentry-nextjs-sdk` |
**Distributed tracing setup** — if the backend skill is added, configure `tracePropagationTargets` in Android to propagate trace context to your API:
```kotlin
options.tracePropagationTargets = listOf(
"api.yourapp.com",
".*\\.yourapp\\.com"
)This links mobile transactions to backend traces in the Sentry waterfall view.
ls ../ios ../YourApp-iOS 2>/dev/null
find .. -maxdepth 3 -name "*.xcodeproj" 2>/dev/null | head -3
如果存在未配置Sentry的后端或关联平台,推荐使用对应的技能:
| 检测到的项目 | 推荐技能 |
|----------|--------------|
| Go后端(`go.mod`) | `sentry-go-sdk` |
| Python后端(`requirements.txt`、`pyproject.toml`) | `sentry-python-sdk` |
| Ruby后端(`Gemfile`) | `sentry-ruby-sdk` |
| Node.js后端 | `@sentry/node` — 参考[docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |
| iOS应用(`.xcodeproj`) | `sentry-cocoa-sdk` |
| React Native(`package.json`包含`react-native`) | `sentry-react-native-sdk` |
| React / Next.js前端 | `sentry-react-sdk`或`sentry-nextjs-sdk` |
**分布式追踪配置** — 如果同时配置了后端技能,在Android端配置`tracePropagationTargets`将链路上下文传播到你的API:
```kotlin
options.tracePropagationTargets = listOf(
"api.yourapp.com",
".*\\\\.yourapp\\\\.com"
)这会将移动端事务和后端链路在Sentry的瀑布流视图中关联起来。
Troubleshooting
问题排查
| Issue | Solution |
|---|---|
| Events not appearing in Sentry | Set |
| Confirm |
| Gradle plugin not found | Add the plugin to project-level |
| ProGuard mapping not uploading | Set |
| NDK crashes not captured | Verify |
| ANR reported in debugger | Set |
| Session replay not recording | Requires API 26+; verify |
| Session replay shows blank screen | PixelCopy (default) requires hardware acceleration; try |
| Replay masking misaligned | Views with |
| |
| OkHttp spans not appearing | Add |
| Spans not attached to transaction | Ensure |
| Tracing not recording | Verify |
| Continuous profiling not working | SDK ≥ 8.7.0 required; API 22+ required; set |
| Both profiling modes set | |
| TTFD spans missing | Set |
| Kotlin coroutine scope lost | Add |
| Release build stack traces unreadable | ProGuard mapping not uploaded; confirm Gradle plugin |
| Source context not showing in Sentry | Enable |
| BOM version conflict | Use |
| Auth token is build-time only — never pass it to |
| 问题 | 解决方案 |
|---|---|
| Sentry中看不到事件 | 设置 |
| 确认 |
| 找不到Gradle插件 | 先在项目级 |
| ProGuard映射未上传 | 设置 |
| 捕获不到NDK崩溃 | 确认 |
| 调试器中上报ANR | 设置 |
| 会话回放不录制 | 需要API 26+;确认 |
| 会话回放显示黑屏 | PixelCopy(默认)需要硬件加速;尝试设置 |
| 回放屏蔽位置偏移 | 带有 |
| |
| 看不到OkHttp span | 向 |
| Span没有关联到事务 | 启动事务时设置 |
| 链路追踪不生效 | 确认 |
| 持续性能剖析不工作 | 需要SDK ≥ 8.7.0;API ≥ 22;设置 |
| 同时配置了两种剖析模式 | |
| 缺少TTFD span | 设置 |
| Kotlin协程scope丢失 | 添加 |
| Release构建堆栈不可读 | ProGuard映射未上传;确认Gradle插件中 |
| Sentry中看不到源码上下文 | (需要Gradle插件)在 |
| BOM版本冲突 | 使用 |
| Auth token仅构建时使用 — 绝对不要传递给 |
| ", |