Android StrictMode: Catch Issues Before They Reach Production
Learn how StrictMode helps detect performance bottlenecks, resource leaks, and bad practices before they reach production.
StrictMode is a developer tool in Android that helps detect and flag potential problems in your app’s code during development. It’s a runtime policy checker that catches accidental violations that could lead to performance issues or bugs.
StrictMode monitors two main categories of violations:
Thread Policy Violations: Detects operations on the main/UI thread that can cause frame drops or ANRs.
Disk reads/writes on the main thread
Network operations on the main thread
Custom slow code execution
VM Policy Violations: Detects memory and resource-related issues in the app.
Activity leaks
SQLite object leaks
Closeable object leaks
Using StrictMode
Example code to enable from early in your Application, Activity, or other application component’s onCreate() method:
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}Note: Always enable StrictMode only in debug builds, never in production.
You can decide what should happen when a violation is detected. For example, using penaltyLog(), you can watch the output of adb logcat while you use your application to see the violations as they happen.
Few methods are:
penaltyDeath(): Crash the whole process on violation.
penaltyDeathOnNetwork(): Crash the whole process on any network usage.
penaltyDialog(): Show a dialog to the developer on detected violations.
penaltyFlashScreen(): Flash the screen during a violation.
penaltyLog(): Log detected violations to the system log.
By integrating StrictMode into your workflow, you can build more efficient and responsive Android apps.
We must know that it is not a silver bullet. It won’t catch everything, but it helps identify common mistakes like:
Main-Thread Disk I/O
Main-Thread Network Calls
Resource Leaks
Slow Operations
Start using StrictMode from now onwards.
Prepare for your Android Interview: Android Interview Questions and Answers
Thanks
Amit Shekhar
Founder, Outcome School


