Use StrictMode To Find Things You Did By Accident In Android Development

As long as we are human, we are bound to make mistakes.

Mistakes are always forgivable, if one has the courage to admit them : Bruce Lee

So, how do you know and correct your mistakes done during android app development? Android provides a tool for that.

StrictMode to the rescue!

StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.

StrictMode is most commonly used to catch accidental disk or network access on the application’s main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application’s main thread responsive, you also prevent ANR dialogs from being shown to users.

So how do you use the method? Well it’s pretty simple:

Example code to enable from early in your Application, Activity, or other application component’s onCreate() method:

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 an annoying dialog to the developer on detected violations.
  • penaltyFlashScreen(): Flash the screen during a violation.
  • penaltyLog(): Log detected violations to the system log.

If you find violations that you feel are problematic, there are a variety of tools to help solve them: threads, Handler, AsyncTask, IntentService, etc. But don’t feel compelled to fix everything that StrictMode finds. In particular, many cases of disk access are often necessary during the normal activity lifecycle. Use StrictMode to find things you did by accident.

StrictMode can be used to enable and enforce various policies that can be checked for and reported upon. These policies generally include best-practice type coding issues, such as monitoring for actions done on the main thread that shouldn’t be and other naughty or lazy coding practices.

StrictMode has various policies. Each policy has various rules. Each policy also has various methods of showing when a rule is violated.

So, start using StrictMode from now onwards.

Complete RxJava Tutorial

RxJava is a Java VM implementation of Reactive Extensions. It has become the single most important skill for Android development.

Just login here and learn RxJava.

Happy Coding 🙂


Also, Let’s become friends on Twitter, Linkedin, Github, and Facebook.


Amit Shekhar

Amit Shekhar

Co-Founder at Mindorks | Learning is a journey, let’s learn together