Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Keeping Your App Snappy with StrictMode

Author: Adrian Cowham
Published? true
FormatLanguage: WikiFormat

Problem:

Making sure your app's GUI is as snappy as possible isn't easy. But with the help of Android's StrictMode it doesn't seem all that bad.

Solution:

Android has a tool called Strict Mode that they introduced in Gingerbread, Strict Mode will detect all cases where an ANR might occur. For example, it will detect and log to LogCat all database reads and writes that happen on the main thread (i.e. the GUI thread).

Discussion:

I wish I could've used a tool like StrictMode back when I was doing Java Swing Desktop development. Making sure our Java Swing App was snappy was a constant challenge, green and seasoned engineers would invariably perform database operations on the UI thread that would cause the app to hiccup. Typically we found these hiccups when QA ( or customers ) would use the app with a larger dataset than the engineers were testing with. Having QA find these little defects was unacceptable and ultimately a waste of everyone's time ( and the company's money ). We eventually solved the problem by investing more heavily in peer reviews, but having a tool like StrictMode would have been comparatively cheaper.

The example code below illustrates how easily StrictMode can be turned on in your app.

// make sure you import StrictMode
import android.os.StrictMode;

// In you app's android.app.Applicatoin instance, add the following
// lines to the onCreate(...) method.
if ( Build.VERSION.SDK_INT >= 9 && isDebug() ) {
  StrictMode.enableDefaults();
}

Please note that the isDebug() implementation has been intentionally omitted, as this will vary among developers. I recommend only enabling StrictMode when your app is in Debug mode, it's unwise to put your app in the Market with StrictMode running in the background and consuming resources unnecessarily.

StrictMode is highly configurable, it allows you to customize what problems to look for. For detailed information on customizing StrictMode policies, see the StrictMode link below.

See Also:

http://developer.android.com/reference/android/os/StrictMode.html

No records found.