tutorial, no_image, android,

Android - no_image

Upendra Upendra Follow Jan 23, 2025 · 1 min read
Android - no_image
Share this

StrictMode

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.1

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

override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     StrictMode.setThreadPolicy(
         StrictMode.ThreadPolicy.Builder()
         .detectAll()
         .build()
     )
     StrictMode.setVmPolicy(
         StrictMode.VmPolicy.Builder()
         .detectAll()
         .build()
     )
 }

You can decide what should happen when a violation is detected. For example, using StrictMode.ThreadPolicy.Builder.penaltyLog() you can watch the output of adb logcat while you use your application to see the violations as they happen.2

Penalty Types

StrictMode uses penalties to signal violations:

  • penaltyLog(). Logs the violation in the system logcat, making it easy to see what went wrong;
  • penaltyDeath(). A drastic measure, forcing the app to crash on a violation. Useful for catching severe problems immediately;
  • penaltyDialog(). This would display a dialog to the user (not typically used in production).

Note: The exact policies offered by StrictMode have evolved over Android versions.

Links

StrictMode

StrictMode: Your Android App’s Watchdog

Further reading

Smooth Operator: Using StrictMode to make your Android App ANR free

Android Best Practices: StrictMode

Raising the Bar with Android StrictMode

credit goes to @swayangjit
Join Newsletter
Get the latest news right in your inbox. We never spam!
Upendra
Written by Upendra Follow
Hi, I am Upendra, the author in Human and machine languages,I don't know to how 3 liner bio works so just Connect with me on social sites you will get to know me better.