May 16, 2016

Strict Mode is a special class introduced in Android 2.3 for debugging. This developer tools detect things done accidently and bring them to our attention so that we can fix them. It is most commonly used to catch the accidental disk or network access on the applications’ main thread, where UI operations are received and animations takes place. On the main thread we should not keep our main operations to be performed, or a bigger operations to be performed. Keeping these types of task out of the way of Main Thread, makes your applications smoother.
StrictMode is basically a tool to catch the bug in the Compile Time mode. However, we should not allow ourselves to resolve all the scenarios the StrictMode suggests. Sometimes we should just give our applications the permission to perform those operations. StrictMode is used to setup thread and virtual machine policies for our application and report violations for such policies.

There are two types of policies available in StrictMode.

A. Thread Policy
B. Virtual Machine Policy

A. Thread Policy :
Thread Policy are concerned with the non-recommended things that are done on the main UI Thread. Violations that can took place in Thread Policy are :

  1. a). Disk Reads
  2. b). Disk Writes
  3. c). Network Access
  4. d). Slow Calls
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.penaltyLog() //Logs a message to LogCat
.build());

The above Code Snippet is to setup the StrictMode for Thread Policies. This Code is to be set at the entry points to our application.
B. VM Policy :
This policy deals with leaks of memory, like it detects when in SQLLite finalize is called or not. Or any Closeable object is finalized before it has been closed. The Code Snippet for this policy is like this :

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

Some of the policy violations for VM Policy violations are like these :

  1. a). detectActivityLeaks() added in API 11, it will check the leak of Activity subclasses.
  2. b). detectLeakedCloseableObjects(), it will detect when an object with a explicit termination method is finalized without having been closed.
  3. c). setClassInstanceLimit, added in API 11, this sets an upper limit of how many instances of a class can be in a memory at once.

If you find violations that you feel are problematic, there are a
variety of tools to solve them such as, threads, Handler, Asynctask, IntentService etc.
But we shouldn’t try to solve all violations that our StrictMode detects.