Android StrictMode for Debugging

Android StrictMode for debugging

strictmode.png?w=2924

Introduction

Android provides a handy tool for developers to see what happened to their Apps. Sometimes, you just forgot to keep massive loading job off the main UI thread, e.g., network access, database query, or something you need much time to handle, in these cases, you usually got ANR dialogs to notify you: Your App is going to spend too much time on something in UI thread.

But sometimes, we ignore these signals and release our App, and then you received many complaints from customer emails, comments on Google Play, and weird crash from Crashlyitcs.

So, how do we solve these problems? Can any tools help us to monitor these cases? Yes, we can use StrictMode to check the current status in our project. The StrictMode would detect things that should not run in the main thread, for example, the network loading, massive disk accessing, and those actions make the UI not responsiveness to users.

Here is the StrictMode Introduction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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();
}

Remember, you should enable that in your Application, Activity, or other application component’s onCreate() method, or it would not work.

There are two different types of monitoring here:

  1. for threads
  2. for VMs.

That means you can monitor some heavy loading jobs on UI thread, or check leaks on VMs. Both are useful. I would suggest you should open two detection policies for both thread and VM. But I need to emphasize that StrictMode is not a security mechanism, it’s just a helper tool. So, I suggest that you, developers, should combine other tools to check/analyze your Apps.

There are a lot of policies you can use, please refer to descriptions here. The most interesting thing is you can send penalty logs to your Dropbox account, so, all you need to do is connect to your Dropbox account with your phone, and start testing.

Happy coding, enjoy.

[Reference]

  1. YouTube: Google Best Practices - StrictMode
  2. Android Developers Blog: StrictMode API for Built-In Performance Monitoring