Android Dev Tool: Best practice with StrictMode





StrictMode (android.os.StrictMode) is a developer tool which detects things you might be doing wrong by accidently and brings them to your attention.

Best practice in Android says “keeping the disk and network operations off from the main thread makes applications much smoother and more responsive”.  So StrictMode is use to catch the coding issues such as disk I/O or network access on the application's main thread i.e. UI thread.

This is a debugging tool introduced in Android 2.3(API level 9) but more features were added in Android 3.0.


StrictMode Policies

StrictMode has two types of policies and each policy has various rules.
1.    Thread policy
2.    VM policy

Thread Policy-

Thread policies are focused on the things which is not recommended to do in main thread like disk or network operations. The thread policy can monitor following violations:

·       Disk Reads
·       Disk Writes
·       Network access
·       Resource Mismatch
·       Custom Slow Code


VM Policy-

VM policies are focused on memory leaks because of bad coding practices like forgot to close the SQLite cursor or leaks in Activities. The VM policy can monitor following violation:

·       Activity leaks
·       SQLite objects leaks
·       Closable objects leaks
·       Registration objects leaks
·       Class instance limit
·       File URL exposure


Ways to notify

There are variety of different ways by which user/developer get to know when a rule you set has been violated. In terms of StrictMode it is known as Penalty. Some of them are listed below-

penaltyLog(): Log the detected violations into the system log.
penaltyDeath(): Crash the whole process when violation of rule found.
penaltyDialog(): Display a dialog for detected violations.
penaltyDeathOnNetwork(): Crash the whole process on any network usage.
penaltyDropBox(): Enable detected violations log a stacktrace and timing data to the DropBox on policy violation.
penaltyFlashScreen(): Flash the screen during a violation.


How to use

To enable and configure the StrictMode in your application, you require to use setThreadPolicy() and setVmPolicy() methods of StrictMode.  It is a good practice to set policies either in Application class or initial activity.

Here is the example of Thread Policy:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()  
                 .penaltyLog()
                 .build());

Here is the example of VM Policy:
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());

You can decide what should happen when a violation is detected like in the above example we have used only penaltyLog() for Thread Policy but in the VM Policy we used penaltyLog() as well as penaltyDeath() to notify.

Here is the example of penaltyLog() showing the logs which explains StrictMode is warning us that we are using disk write operation on the main thread.

DEBUG/StrictMode(23134): StrictMode policy violation; ~duration=319 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=31 violation=1
DEBUG/StrictMode(23134):     at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1041)
DEBUG/StrictMode(23134):     at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:219)
DEBUG/StrictMode(23134):     at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:83)
DEBUG/StrictMode(23134):     at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1829)
DEBUG/StrictMode(23134):     at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1780)
DEBUG/StrictMode(23134):     at com.test.data.MainActivity.update(MainActivity.java:87)


And here is the warning dialog looks like:



Ignore Policies

Don't try to fix everything that StrictMode finds. In most of the cases we access the disk to quickly read some data from Activity or main thread. It won’t create noticeable glitch or hanging behavior in the application UI. So instead use the StrictMode to find things you did by accident.


Conclusion

As we have seen StrictMode is a very useful tool to find and fix performance issues, object leaks, and other hard-to-find runtime issues for Android developers.  
If you find violations that you feel are problematic, there are a variety of tools to help solve them like threads, Handler, AsyncTask, IntentService, etc.
For more info on StrictMode policies and rules, please go through Android Official page.


  
To find more interesting topics on Software development follow me at https://medium.com/@ankit.sinhal.

Twitter: https://twitter.com/ankitsinhal

Comments

Popular posts from this blog

Android O: Impact On Running Apps And Developer Viewpoint

Android Performance: Avoid using ENUM on Android

Local Broadcast, less overhead and secure in Android