乐闻世界logo
搜索文章和话题

What is ANR in Android and how to diagnose and solve ANR issues

3月6日 23:09

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

TypeTrigger ConditionTime Limit
Input ANRKey or touch event not responding5 seconds
BroadcastReceiver ANRonReceive() timeoutForeground 10s, Background 60s
Service ANRService lifecycle method timeout20 seconds
ContentProvider ANRContentProvider operation timeout10 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

shell
E/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

java
StrictMode.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

java
HandlerThread 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
标签:Android