StrictMode: Your Main Thread's Watchdog
StrictMode is a developer tool that acts like a strict supervisor for your app's main thread, catching slow operations like disk or network access. It helps you find performance issues before they cause "Application Not Responding" errors.
WHY IT EXISTS: The Android main thread is responsible for handling UI events and drawing. If you perform long-running tasks like reading a file or making a network request on it, the UI freezes. This leads to a poor user experience and "Application Not Responding" (ANR) dialogs. StrictMode was created to help developers find these violations during development, before they affect users.
THE MENTAL MODEL: Think of StrictMode as a "nanny" for your app's main thread. You tell it the rules, like "no disk access" or "no network calls," and if the main thread breaks those rules, the nanny will tattle. It reports violations by logging to the console, flashing the screen, or even intentionally crashing the app, forcing you to fix the problem.
HOW IT WORKS: You enable StrictMode programmatically, typically in your Application or Activity's onCreate method. You configure policies for two different areas. First, a ThreadPolicy defines rules for the main thread, such as detecting disk reads, disk writes, or network requests. Second, a VmPolicy defines rules for the virtual machine, like detecting leaked SQLite cursors or unclosed resources. For each violation, you can specify a penalty, such as logging the stack trace (penaltyLog()) or crashing the app (penaltyDeath()).
WHEN TO USE IT: Use StrictMode exclusively during development and testing. It's an invaluable tool for catching performance bottlenecks and potential sources of ANRs early in the development cycle. It helps enforce good practices by making sure long-running work is offloaded to background threads.
WHEN NOT TO USE IT: Never enable StrictMode in production builds. The penalties are designed to be disruptive for developers, not end-users. Even with logging-only penalties, it adds performance overhead that is unnecessary for a shipped application. Always wrap your StrictMode setup in a check like if (BuildConfig.DEBUG).
ONE CANONICAL EXAMPLE: In your Application class's onCreate method, you might add the following for a debug build: if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); }. This setup will watch for any disk or network operations on the main thread and print a detailed stack trace to Logcat when one occurs.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.