What is StrictMode?
It's a developer tool introduced in Gingerbread that is mostly used to detect lengthy operations running on your application's main thread, such as disk reads/writes and network access. It can also catch leaked SQLite cursors and resources that have not been properly closed. You can display an annoying dialog when a violation happens, log it or just crash the entire application. There are several articles describing StrictMode in detail, so go read them first.
The configuration used was the proposed in the reference documentation:
public void onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(); }
What did we find?
- Disk access
Calls to getReadableDatabase and getWritableDatabase were also considered to be violations. The documentation of SQLiteOpenHelper states that both these methods should not be called from the application main thread, so this was something new.
There were a lot of image files accidentally being read from the filesystem within the main thread. The fix was simple and the impact in performance was huge.
- Leaked cursors
- Network access
- Other issues found unrelated to responsiveness
Conclusion
StrictMode is an invaluable tool that should be enabled from the beginning of every project. We are currently enabling it in all our ongoing projects and it's helping to make us feel a little less stupid every time we catch something right on the first launch.
StrictMode is an invaluable tool that should be enabled from the beginning of every project. We are currently enabling it in all our ongoing projects and it's helping to make us feel a little less stupid every time we catch something right on the first launch.