jbww jbww - 6 months ago 14
Android Question

better way to do Debug only assert code

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 = ...

if (mDebug)
Assert.assertNotNull(view);

Is there a better way to do this? i.e. I would prefer not to use an if() with each assert.

thanks

Answer

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:

  1. Checks whether the static variable assertionsDisabled (set in the class' static constructor via a call to java.lang.Class.desiredAssertionStatus()) is != 0 and if so, does nothing
  2. If it is 0, then it checks the assertion expression and throws a java.lang.AssertionError if 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?