Sunday, April 28, 2013

How to avoid unstable releases - StrictMode

The following method is less about finding bugs per se, than finding violations of best practices (most importantly: no I/O on the main thread!). It's called StrictMode and has been introduced in Android 2.3 (Gingerbread).

Using it is really simple. Let's say you want to find out if and where you do I/O on the main thread, you'd add the following code in your onCreate:

   StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());

.setPenaltyDeath()
Everytime an I/O operation is executed from the main thread, a stacktrace will pop up in LogCat, telling you exactly where you violated the "policy". By the way, you can filter these messages using "tag:StrictMode".
If the log is not enough for you, you can add additional penalties, like .penaltyDialog (shows a dialog on violations) and .penaltyFlashscreen (only available on newer devices). You can even kill the app: .penaltyDeath (ouch!).

Furthermore, you can set a policy for memory leaks, such as unclosed resources (InputStream, etc):

   StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());

The same tips as above apply for this policy.

For more tips on improving the performance of your app, see the "Best Practices for Performance", especially "Performance Tips" and "Keeping Your App Responsive".

No comments:

Post a Comment