anr-detective
v1.2.3
Published
Static code scanner and diagnostic tool to find and eliminate Android Application Not Responding (ANR) risks.
Downloads
640
Maintainers
Readme
🕵️♂️ ANR Detective
ANR Detective is a professional diagnostic, static scanning, and auto-patching toolkit designed to eliminate Application Not Responding (ANR) errors, thread deadlocks, and slow startup bottlenecks in Android applications.
Whether you're dealing with cryptic production traces from the Google Play Console, laggy main thread frames, or complex lock contentions, ANR Detective acts as your dedicated specialist—pinpointing root causes, scanning codebases for dormant risks, and generating safe, modern Kotlin/Java asynchronous patches.
🚀 Key Features
- ⚡ Trace & Logcat Diagnosis: Parse raw stack traces, tombstone files, system logcats, and bug report
.zipfolders to reveal exactly where the main thread was blocked. - 🔍 Proactive Code Scanner: Static analysis of high-risk components (Activities, Services, BroadcastReceivers, ContentProviders, and Application classes) to catch blocking calls before they hit production.
- 🛠️ Safe Asynchronous Auto-Patching: Generates drop-in replacements using Kotlin Coroutines, modern Jetpack standards (Room, DataStore), or classic Java
ExecutorServicepatterns. - 🛡️ Active Guard Mode: Automatically reviews thread context and audits newly written or modified Android code for blockages in lifecycle events.
🗺️ How It Works (ANR Detective Workflow)
The diagnostic and resolution pipeline follows a structured flow from intake to verification:
graph TD
A[Input: Trace, Logcat, ZIP, or Codebase] --> B{Determine Mode}
B -->|Trace/Logcat provided| C[Diagnose Mode]
B -->|Codebase provided| D[Scan Mode]
C --> C1[Identify ANR Type & Timeout]
C --> C2[Perform Root Cause Analysis]
C --> C3[Locate Thread/Lock Culprit]
C3 --> E[Diagnosis Report]
D --> D1[Scan Application, Activity, Service, Receiver, Provider]
D --> D2[Apply Severity Checklist]
D2 --> F[Static Risk Scan Report]
E --> G[Fix Mode]
F --> G
G --> G1[Generate Safe Async Patches]
G1 --> H[Verification: StrictMode, Perfetto, CPU Profiler]📁 Repository Structure
SKILL.md: The core AI agent skill definition. It configures LLM assistants to act as expert ANR diagnostics and auto-patching agents across four distinct operation modes.references/anr-patterns.md: Detailed trace signatures, timeout budgets, common causes, and code snippets for 12 major ANR classes (including Input Dispatch, Broadcast, Service, Binder, Deadlocks, No-Focused-Window, and Slow Job Response).references/fix-strategies.md: A canonical directory of "before/after" code changes demonstrating how to move blocking ops off the main thread in both Kotlin (Coroutines, Flow) and Java.
📖 Operational Modes
ANR Detective operates dynamically depending on the input provided:
1. 🔍 Diagnose Mode
Takes raw logs or dumps and breaks down the exact thread states.
- Supported Inputs: Google Play Console ANR traces, logcat entries, tombstone native reports, and raw Android Bug Report
.ziparchives (parsingFS/data/anr/andbugreport-*.txt). - Output: A structured, plain-English report detailing the ANR type, timeout limit, exact file/method culprit, callstack breakdown, contributing factors (e.g., lock contention, binder saturation), and recommended fixes.
2. 🕵️ Scan Mode
Runs static analysis of source code files, prioritizing high-risk entry points.
- Application Class (
Application.onCreate): Blocks all app startups. Blocking calls here are labeled Critical regardless of duration. - Activities & Fragments: Scanning crucial lifecycle methods (
onCreate,onResume,onStart). - Services & JobServices: Ensuring initialization and job starts offload computational tasks.
- BroadcastReceivers: Identifying receivers running on the main thread that exceed the 10s foreground budget.
3. 🛠️ Fix Mode
Generates safe, compiler-compliant patches matching the exact Kotlin/Java guidelines of your project.
- Kotlin-First: Utilizes structured concurrency (
viewModelScope,lifecycleScope,withContext(Dispatchers.IO)). - Java Fallback: Uses robust
ExecutorServiceandHandler(Looper.getMainLooper())setups. - Receiver Optimizations: Correctly hooks up
goAsync()or applies off-thread custom handlers (registerReceiverwith a background Handler).
4. 🛡️ Guard Mode (Proactive Review)
Runs automatically in agent workflows. Before presenting newly written or modified Android code, it audits the code's thread context. If a blocking I/O, sync block, or heavy computation is detected inside a main-thread-bound method, it automatically rewrites the code using safe async blocks before presentation.
🚨 ANR Risk Checklist & Severity Levels
Static scans categorize code smells based on their potential to block the main thread and trigger an OS-level ANR dialog:
| Risk Pattern | Severity | Impacted Area | Recommended Alternative |
|:---|:---:|:---|:---|
| Network call on main thread | 🔴 Critical | Network / API | Move to Coroutines on Dispatchers.IO / Async OkHttp |
| File / Database I/O on main thread | 🔴 Critical | Storage / Room | Suspend functions / lifecycleScope / loaders |
| Wait on Latch or Future on main thread | 🔴 Critical | Threading | Replace latch.await() and Future.get() with coroutines |
| Broadcasting / Service heavy logic | 🟠 High | Broadcast / Service | Use goAsync() or offload to background threads |
| Deadlock Risk / Monitor Contention | 🟠 High | Concurrency | Standardize lock ordering or use concurrent collections |
| Thread.sleep() in main lifecycle | 🟠 High | Lifecycle | Replace with coroutines delay() |
| Synchronous SharedPreferences.commit() | 🟡 Medium | Storage | Swap with apply() or upgrade to Jetpack DataStore |
| Tight Binder / IPC loop in lifecycle | 🟡 Medium | System API | Cache system service results, offload query to thread |
💻 Command-Line Interface (CLI)
ANR Detective can be run directly from your terminal to scan directories locally. This makes it perfect for manual audits and automated CI/CD pipelines.
Quick Start (npx)
You do not need to install the package to run a scan. Simply execute:
npx anr-detective --path /path/to/android/projectGlobal Installation
Alternatively, install it globally via npm:
npm install -g anr-detectiveAnd run it inside any project directory:
anr-detectiveOptions & Flags
Configure the CLI execution to fit your environment:
--install, -i, install: Runs the interactive setup manager, allowing you to select and install the ANR Detective skill for Claude Code, Copilot, Trae, Cursor, Windsurf, Aider, Warp, or Gemini using a beautiful keyboard-controlled checkbox menu.--path <dir>: Target folder to scan or configure (defaults to your current working directory).--json: Outputs results strictly as a JSON object, making it easy to parse in build pipelines or reporting dashboards.--fail-on <severity>: Specifies the threshold level that causes a non-zero exit code (1). Options arecritical,high, andmedium(default:critical).
🤖 AI Assistant & Editor Setup
To easily register the ANR Detective AI Skill with your favorite coding tools, run:
npx anr-detective install(Alternatively, you can run npx anr-detective --install or npx anr-detective -i)
[!TIP] The setup manager uses a premium interactive terminal checkbox layout. Use the Up/Down Arrow Keys to navigate, press
[Space]to check/uncheck options,[A]to select/deselect all, and press[Enter]to confirm and run!
This interactive utility will guide you through setting up rules for:
- Global Agent Skills: Configures a global custom skill folder under
~/.agents/skills/anr-detective(including all reference patterns and fix strategies). - Gemini / Antigravity: Configures a global custom skill folder under
~/.gemini/antigravity/skills/anr-detective(including all reference patterns and fix strategies). - Claude Code: Configures custom rules (
CLAUDE.md) AND copies the modular agent skill folder to~/.claude/skills/anr-detective(global) or.claude/skills/anr-detective(local). - GitHub Copilot: Configures repository-wide rules (
copilot-instructions.md) AND copies the modular agent skill folder to.github/skills/anr-detective(local) or~/.copilot/skills/anr-detective(global). - Cursor Editor: Generates custom rules (
.cursorrules) AND copies the modular agent skill folder to.cursor/skills/anr-detective. - Windsurf Editor: Generates custom rules (
.windsurfrules) AND copies the modular agent skill folder to.windsurf/skills/anr-detective. - Trae Editor: Configures rules (
./.trae/rules/project_rules.md) AND copies the modular agent skill folder to.trae/skills/anr-detective. - Warp Terminal: Configures Warp AI codebase rules locally at
./WARP.md. - Aider Agent: Exports custom instructions to
~/.aider.instructions.md.
🛠️ Integrating ANR Detective into your Workflow
With AI Coding Assistants (e.g. Gemini, Claude, Cursor)
This repository includes a fully-formed AI Agent Skill in SKILL.md. You can load this directory or copy the skill instructions into your assistant's system instructions.
When loaded, you can prompt your assistant:
"Scan my current package for any latent ANR risks."
"Here is an ANR trace from my Play Console. Run Diagnose Mode on it and generate the fix."
"Review my BroadcastReceiver inside MyReceiver.kt. Does it require goAsync()?"
🧪 Recommended Verification Pipeline
After applying any async patches recommended by ANR Detective, run these four checks to ensure thread safety:
- Enable StrictMode in Debug Builds:
Catch regressions instantly during manual QA by adding this to your
Application.onCreateor launcherActivity.onCreate:if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build() ) } - Lint Thread Audit:
Run
./gradlew lintand review allWrongThreadandMainThreadcompiler alerts. - Trace Thread States with Perfetto / Profiler: Profile CPU usage via Android Studio Profiler or Perfetto. Ensure the Main Thread's thread state track remains green (Running) and doesn't sit in orange/red (Blocked/Sleeping) during user interactions.
- Confirm Async Broadcast Boundaries:
If using
goAsync(), make surependingResult.finish()is strictly called in afinallyblock to prevent leaking wakelocks and causing secondary ANRs.
📄 License
This repository is licensed under the MIT License. See LICENSE for details.
