Android中使用StrictMode能否避免ANR?附配置及测试代码
Hey there! Great question—let’s cut to the chase first: StrictMode does NOT directly avoid or prevent ANRs (Application Not Responding errors). Instead, it’s a powerful debugging tool that helps you catch the root causes of potential ANRs early during development, so you can fix them before they impact users.
Let’s break down how this works:
StrictMode’s core job is to detect when your app performs blocking, time-consuming operations on the main thread (like disk reads/writes, network calls, or heavy computations). The penalties you’ve set up in your code—penaltyLog(), penaltyFlashScreen(), penaltyDeath()—are just immediate alert mechanisms for these violations:
penaltyLog()writes warnings to Logcat, letting you spot issues while debugging.penaltyFlashScreen()gives a visual cue on the device to grab your attention.penaltyDeath()crashes the app right away, forcing you to address the problem immediately (perfect for development, but definitely not something you want in production!).
A quick note on your configuration code:
public class MyApplication extends Application { @Override public void onCreate() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .penaltyFlashScreen() .penaltyDeath() .detectDiskReads() .detectDiskWrites() .detectNetwork() .build()); super.onCreate(); } }
You don’t need to call detectDiskReads(), detectDiskWrites(), or detectNetwork() after detectAll()—detectAll() already includes all those checks. It’s harmless redundancy, but you can clean that up for better code clarity.
Why StrictMode can’t stop ANRs directly
ANRs trigger when the main thread is blocked for too long (usually 5+ seconds, depending on the scenario). If you ignore StrictMode’s warnings and leave blocking operations on the main thread, those operations will still block the thread, and eventually trigger an ANR. StrictMode doesn’t magically fix the issue—it just tells you where the issue is.
How to actually avoid ANRs
To prevent ANRs, you need to fix the underlying issues StrictMode flags:
- Move all disk I/O, network requests, and heavy computations to background threads (use Kotlin Coroutines,
ExecutorService, orWorkManager—avoid the deprecatedAsyncTask). - Keep main thread work focused solely on UI updates and lightweight logic.
- Use StrictMode during development to catch violations early, then disable harsh penalties like
penaltyDeathin production builds (wrap StrictMode setup in aBuildConfig.DEBUGcheck to automate this).
内容的提问来源于stack exchange,提问作者Gajanand Swamy

