Assertions on Android
Sunday, April 08, 2012, Modified: Tuesday, September 18, 2012 Refs

Enabling Assertions on Android

Assertions can be turned-on from a terminal running on the device if you are root.
su
setprop debug.assert 1
Alternatively, you can do the same thing from the host using adb:
adb shell setprop debug.assert 1
If you are developing on your day to day device, this does make Google maps less usable though as they have assertions in place that will bring down that app.

Enhancing Assertions on Android

The bytecode for assertions will stay in a release build (http://stackoverflow.com/a/5590378/506073). I don't believe the javac compiler can be told not to emit assertions so they need to be stripped-out somehow. A simple solution to that is to wrap the keyword assert in your own function that proguard can strip for you.

Such a wrapper can be made to do a bit more as well such as logging the file and line of the error even when the assert keyword is disabled. For example:
   private static final int ASSERTION_LEVEL = 1;
   private static final boolean DEV_CODE_ENABLED = true;
   // ...
   public static void assert1(final boolean val)
   {
      if(ASSERTION_LEVEL >= 1 && DEV_CODE_ENABLED) {
         assert val;
         if(!val){
            final StackTraceElement elem = callers_caller();
            logE(elem.getClassName(), annotate_msg("ASSERTION FAILED (Level 1). Line: ", elem));
         }
      }
   }

   private static StackTraceElement callers_caller(){
      final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
      final StackTraceElement elem = trace[4];
      return elem;
   }

 /** Take a user message and decorate it with file and line number information.
    * In release builds the decoration is omitted and the message passes through
    * unchanged. */
   private static final String annotate_msg(final String msg, final StackTraceElement elem){
      final String safe_msg = msg != null ? msg : "";
      if(DEV_CODE_ENABLED)
      {
         final String annotated_msg = safe_msg + ". On line: " + elem.getLineNumber() + " of file " + elem.getFileName();
         return annotated_msg;
      } else {
         return safe_msg;
      }
   }

Try Buffer, a smarter way to share links and pictures by spreading your tweets and posts out over time. Sign up from this link and we both get extra features.

Buffer
Home :: Items