Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BuildConfig.DEBUG (or equivalent) as a constant value

Assuming I have a custom annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Test {
    boolean type();
}

I would like for the type parameter to be different based on the build type (but that would change automatically).

So I could do something like that:

@Test(type = BuildConfig.DEBUG)
public class Example {
} 

But of course the code of the Example class won't compile because the value for the BuildConfig.DEBUG is not constant.

Anyone has any idea of creating a workaround for this? Maybe specifying some other parameters in gradle? I'm not interested in a solution that would make me manually change the type for the particular build. This way or the other. I'm looking for a way to do it automatically with the build.

like image 270
Bartek Lipinski Avatar asked Nov 21 '25 08:11

Bartek Lipinski


1 Answers

By gradle android plugin

You can use gradle buildConfigField. For example

android {
    ...
    buildTypes {
        debug {
            buildConfigField "boolean", "TYPE", "true"
        }
        release {
            buildConfigField "boolean", "TYPE", "false"
        }
        ...
    }    
}

and then

@Test(type = BuildConfig.TYPE)
public class Example {
} 

With buildConfigField you can also add some other type to your BuildConfig.

android {
    buildTypes {
        debug {
            buildConfigField "int", "A_INT", "1"
            buildConfigField "String", "A_STRING", "\"string_1\"" // <---note the escape
        }

        release {
            buildConfigField "int", "A_INT", "2"
            buildConfigField "String", "A_STRING", "\"string_2\""
        }
    }
}

and if you have multiple flavors, you can define a field in each flavor:

productFlavors {
    // Define separate dev and prod product flavors.
    dev {
        buildConfigField "boolean", "IS_DEV", "true"
    }

    prod {
        buildConfigField "boolean", "IS_DEV", "false"
    }
}

With the same rules, you can add a value in your resources using resValue:

android {
    buildTypes {
        debug{
            resValue "string", "dev_name", "Alice"
        }

        release {
            resValue "string", "dev_name", "Bob"
        }
    }
}

By Code

You can place a Class with values under src/debug/java/your.package.name and the same Class with different values under src/release/java/your.package.name

debug version

public final class MyConfigurations {
    public static final boolean TYPE = true;
    ...
}

release version

public final class MyConfigurations {
    public static final boolean TYPE = false;
    ...
}

And you can also play with flavors with the same logic of android gradle plugin (and in fact also this solution depends by that plugin)

like image 55
Mimmo Grottoli Avatar answered Nov 22 '25 21:11

Mimmo Grottoli