Recently, Facebook released a tool called Stetho, which let’s you inspect your Android app from the Chrome Developer tools. I find that particularly nifty because it also provides access to any SQLite databases used in the app. Obviously, this type of tools should only be included in debug builds of your app. Here’s a nice way to accomplish that.
Add the dependency
To make sure Stetho is only used for debug builds, add a
debugCompile dependency, in stead of the usual
compile type you’d normally use:
Initialize Stetho in your debug build
Now we actually need to use Stetho in our debug build. How do you do that? By using the awesome powers of the Android Gradle build system!
To add some source that will be only compiled for debug builds, create a new source folder named
src/debug/java. This is just like
but, for the debug variant of your app. In contrast the main folder holds all the source common to all variants.
Then add an Application class as described on the Stetho homepage:
Notice how this class is extended from the main application class already present,
MyApplication. This is really convenient because chances are
that you are already using an application class in your app for other kinds of initialisation. If you don’t have an application, just extend from
The last step is to make sure the debug version of our app actually uses the
MyDebugApplication class. Again, we use the Gradle build to make that happen.
AndroidManifest.xml to the
AndroidManifest.xml will be merged into the main
AndroidManifest.xml file in
src/main and will replace the
<application> tag. It will replace the attribute, because we specified that using the
tools:replace attribute. Pretty neat!
Now when you run the debug build variant of the app, Stetho will be activated. When you switch to the release variant, there will be no trace of it and it won’t be activated. No accidental shipping in release builds, no developer embarrassment.
Using the Android Gradle build system, it's easy to add some extra debug capabilities to your app. This technique doesn’t just work for Stetho, but for any library or tool that you'd like to add for debug only.