Optimize ANR rate using StrictMode in the Android Application

This article explains what is StrictMode and how to use it in Android Applications as an ANR observer.

Narendra Harny
Make Android
4 min readJan 10, 2024

--

What is StrictMode & Why to Use It?

StrictMode is one of the tools that help developers prevent ANR and reduce the chances of ANR being developed in the Android System.

From developer.android.comUsing StrictMode helps you find accidental I/O operations on the main thread while you're developing your app.

We can use the StrictMode as an analyzer tool which works at Runtime to analyze the application process Main Thread. It works based on two policy models and if any policies get violated then it takes respective actions accordingly.

StrictMode Policies!!

Thread Policy:

Disk Read, Disk Write, Network, Resource Mismatch and Slow code

VM Policy:

Activity Leak, SQLite Object, Closable Object, Object Leak, File URL exposure.

As we know ANR is always related to resource-intensive tasks on Main Thread so StrictMode enables all possible reasons that can cause ANR to be considered as a Policy Violation.

How to implement StrictMode?

While learning how to use StrictMode with any Android Process let’s also see a StrictMode policy violation within a practical example.

First, we can create a simple one-page default “Hello world!” Android application and initialize a text view in it.

public class MainActivity extends AppCompatActivity {

TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);

}
}

Let’s perform some heavy operations on the UI thread. So the simplest is I write a while loop and update a text view in it infinitely, which certainly can become a reason ANR for.

@Override
public boolean onTouchEvent(MotionEvent event) {
while(true) {
String s = new String("ABC");
text.setText(s);
}
}

I hope you can see that ANR Dialogue occurs in your Application when the onTouchEvent executes on touching anywhere on the screen.

Now you can add the StrictMode enabling code into the onCreate Method of the main activity.

In principle, this code should be added to the Application class but we don’t have to make it more complex to understand the concept.

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());

Now run the Application and see the Behavior!!

See the output in the below video that when I enabled the StrictMode policy, instead of ANR dialogue the Application crashed straightway and StrictMode Violation was recorded in the Logs.

D  StrictMode policy violation: android.os.strictmode.LeakedClosableViolation: 
A resource was acquired at attached stack trace but never released.
See java.io.Closeable for information on avoiding resource leaks.
Callsite: close
at android.os.StrictMode$AndroidCloseGuardReporter.report(StrictMode.java:1991)
at dalvik.system.CloseGuard.warnIfOpen(CloseGuard.java:338)
at sun.nio.fs.UnixSecureDirectoryStream.finalize(UnixSecureDirectoryStream.java:580)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:319)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:306)
at java.lang.Daemons$Daemon.run(Daemons.java:140)
at java.lang.Thread.run(Thread.java:1012)
W StrictMode VmPolicy violation with POLICY_DEATH; shutting down.
I Sending signal. PID: 20526 SIG: 9
I Process com.example.anrexample (pid 20526) has died: fg TOP
I WIN DEATH: Window{afd4cf6 u0 com.example.anrexample/com.example.anrexample.MainActivity}
I Successfully killed process cgroup uid 10163 pid 20526 in 0ms

As we have seen StrictMode can help to detect the Policy Violations and crash the application.

Conclusion!!!

Android works awesome in handling a lot of problematic situations introduced by applications at runtime and it does the same in terms of ANR also by keeping 5 seconds of torrents of Resource Intensive Task on UI Thread.

However, it is a programmer’s responsibility to follow the standards of programming given by Framework. Because after 5 seconds the ANR become a result of a bad User experience.

So first we need to follow all the coding standards to Prevent the ANR in advance and we can use the StrictMode as a tool if something needs to be improved which is unintentionally left by mistake.

Thanks for Reading!

Please comment with questions and suggestions!! If this blog is helpful for you then hit Please hit the clap! Follow on Medium, Connect on LinkedIn, Follow on Insta and send emails if any discussion is needed on the same topic on copy email.
Please Follow & subscribe to Make Android Publication by Narendra K H for prompt updates on Android platform-related blogs.

Thank you!

--

--

Narendra Harny
Make Android

Connect on https://medium.com/make-android | Write On, Android AOSP & Applications | Python | DevOps | Java | C++ | Kotlin | Shell | Linux | Android Auto | IVI