Change constant values when building a release edition
Asked Answered
D

2

5

I'm developing in eclipse using ADT for android.
In my application I have some constants which help me to to debug my app easily.
As an example I have:
public static final boolean DEBUG_TOAST_LOGS = true;
which help me to toast some logs on the screen.
Each time I intend to build a release, I have to go through my constants and set their values to what is appropriate for the release edition, which is somehow painful.
Now what I want is a way to build my app, using two configurations: one for debug mode and the other for release mode. The release mode should set my constants to the appropriate values. How cant I do that? What's your suggestion? What's the best way to accomplish my need?

Any help would be appreciated.

Drennen answered 28/2, 2015 at 9:50 Comment(0)
F
10

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
        }
        ...
    }
}
Farfamed answered 28/2, 2015 at 11:3 Comment(0)
T
6

@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 ...
}
Teodoor answered 24/10, 2016 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.