I am writing my first Android application and I am liberally using asserts() from junit.framework.Assert
I would like to find a way to ensure that the asserts are only compiled into the debug build, not in the release build.
I know how to query the android:debuggable attribute from the manifest so I could create a variable and accomplish this in the following fashon:
static final boolean mDebug = ...
Is there a better way to do this? i.e. I would prefer not to use an if() with each assert.
I think the Java language's
assert keyword is likely what you want. Under the covers, the
assert keyword essentially compiles into Dalvik byte code that does two things:
assertionsDisabled(set in the class' static constructor via a call to
java.lang.Class.desiredAssertionStatus()) is != 0 and if so, does nothing
java.lang.AssertionErrorif the expression resolves to
false, effectively terminating your application.
The Dalvik runtime by default has assertions turned off, and therefore
desiredAssertionStatus always returns 1 (or more precisely, some non-zero value). This is akin to running in "retail" mode. In order to turn on "debug" mode, you can run the following command against the emulator or the device:
adb shell setprop debug.assert 1
and this should do the trick (should work on the emulator or any rooted debugging-ready device).
Note however that the aforementioned Dalvik code that checks the value of
assertionsDisabled and throws an
AssertionError if the expression is false is always included in your byte code and liberal sprinkling of
asserts in your code may lead to byte code bloat.
Please see this for a bit more detail: Can I use assert on Android devices?