3月6日 23:09
What is ANR in Android and how to diagnose and solve ANR issues
Android ANR Explained
ANR (Application Not Responding) is an error state in Android when an application fails to respond to user input or broadcasts within a specific time period.
ANR Trigger Conditions
| Type | Trigger Condition | Time Limit |
|---|---|---|
| Input ANR | Key or touch event not responding | 5 seconds |
| BroadcastReceiver ANR | onReceive() timeout | Foreground 10s, Background 60s |
| Service ANR | Service lifecycle method timeout | 20 seconds |
| ContentProvider ANR | ContentProvider operation timeout | 10 seconds |
Causes of ANR
1. Main Thread Time-consuming Operations
- Network requests on main thread
- Large database operations
- Complex calculation tasks
- Loading large files or images
2. Deadlock
- Main thread waiting for child thread to release lock
- Child thread waiting for main thread to release lock
3. Insufficient Memory
- System resource shortage
- Frequent GC causing lag
4. Binder Communication Timeout
- Cross-process call timeout
- Server process not responding
ANR Diagnosis Methods
1. Check Logcat
shellE/ActivityManager: ANR in com.example.app E/ActivityManager: Reason: Input dispatching timed out
2. Analyze traces.txt
shell/data/anr/traces.txt
Contains:
- Stack traces of all threads
- ANR occurrence timestamp
- Blocked code location
3. Use Android Studio Profiler
- CPU Profiler to check main thread status
- Identify time-consuming methods
4. StrictMode Detection
javaStrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build());
ANR Solutions
1. Asynchronous Processing
java// Use thread pool ExecutorService executor = Executors.newFixedThreadPool(4); executor.execute(() -> { // Time-consuming operations }); // Use Kotlin coroutines lifecycleScope.launch(Dispatchers.IO) { // Time-consuming operations }
2. Use HandlerThread
javaHandlerThread handlerThread = new HandlerThread("background"); handlerThread.start(); Handler backgroundHandler = new Handler(handlerThread.getLooper());
3. Optimize Database Operations
- Use transactions for batch operations
- Create appropriate indexes
- Avoid querying large data on main thread
4. Avoid Deadlocks
- Unified lock acquisition order
- Use tryLock() instead of lock()
- Reduce lock holding time
Key Points
- ANR is a system protection mechanism, not a crash
- traces.txt is key to diagnosing ANR
- Main thread cannot perform time-consuming operations
- Use Systrace for performance analysis
- Monitor lag and collect online ANR data