Change constant values when building a release edition

ⅰ亾dé卋堺 提交于 2019-12-04 07:10:01

I'm not sure if you are using Gradle as your build system. If you do, you can set build-type specific resources, e.g. a boolean debug value will be true for debug build type, and false for release build type.

build.gradle

android {

    defaultConfig {
        ...
        resValue "bool", "debug", "true"
    }

    buildTypes {
        release {
            ...
            resValue "bool", "debug", "false"
        }
    }

    ...
}

Application.java

public class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if (getResources().getBoolean(R.bool.debug)) {
            ... // debug logic here
        }
        ...
    }
}

@hidro's solution is fine, but requires an unnecessary getResources()... call each time you want to access the value.

There's another possibility :

build.gradle

android {
  buildTypes {
    debug {
      buildConfigField "boolean", "DEBUG_TOAST_LOGS", "true"
    }

    release {
      buildConfigField "boolean", "DEBUG_TOAST_LOGS", "false"
    }
}

}

Then,in your code, you can write :

if (BuildConfig.DEBUG_TOAST_LOGS) {
  // ... enjoy your toasts ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!