Best Way to Include Debug Code?

后端 未结 7 1176
既然无缘
既然无缘 2020-12-24 01:43

I am programming Android applications, and the best way here may or may not be the same as Java in general.

I simply want to be able to set a debug flag that will on

相关标签:
7条回答
  • 2020-12-24 01:46

    Revision 17 of SDK tools (March 2012) introduced a way to imitate C's #ifdef DEBUG

    From the General Notes:

    Added a feature that allows you to run some code only in debug mode. Builds now generate a class called BuildConfig containing a DEBUG constant that is automatically set according to your build type. You can check the (BuildConfig.DEBUG) constant in your code to run debug-only functions.

    0 讨论(0)
  • 2020-12-24 01:58

    Instead of using your own flag, you can use the flag set automatically by ADT, like this:

    final static int appFlags = context.getApplicationInfo().flags;
    final static boolean isDebug = (appFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
    

    The FLAG_DEBUGGABLE bit is automatically set to true or false, depending on the "debuggable" attribute of the application (set in AndroidManifest.xml). The latest version of ADT (version 8) automatically sets this attribute for you when not exporting a signed package.

    Thus, you don't have to remember setting / resetting your own custom flag.

    You can read more in this thread.

    0 讨论(0)
  • 2020-12-24 01:59

    I think that writing tests is better alternative than adding DEBUG code.

    My point is that when you write test for some component/method/class you don't pollute your original source code with some redundant debug code.

    0 讨论(0)
  • 2020-12-24 02:06

    That's the way I do it:

    // in some.class.with.Constants
    public static final boolean DEV_MODE = true;
    
    // in some other class
    import static some.class.with.Constants.DEV_MODE;
    
    if(DEV_MODE){
        Log.d('sometag', 'somemessage');
    }
    
    0 讨论(0)
  • 2020-12-24 02:10

    I suggest to use inbuilt android API BuildConfig

    if (BuildConfig.DEBUG) {
      // do something for a debug build
    }
    
    0 讨论(0)
  • 2020-12-24 02:11

    This works for me with code if (BuildConfig.DEBUG), using the BuildConfig class. This is a safe and easy code to do. Be careful when using this style of code. Don't use it such that there are 2 different distinct branches of code, between Release and Debug versions. If you do, it might invalidate the app testing for the Release version. For me, I have used it only to skip calling Log messaging.

    More details on this class BuildConfig @ Build System Concepts.

    0 讨论(0)
提交回复
热议问题