Reputation: 2249
I build the same Android code from both Android Studio and Visual Studio, and I need a #define in the Java code to compile a line of code differently depending on which environment is doing the build. How can I do this when Java has no #defines?
It would appear that the optimal way to do this would be to define a variable in Gradle based on the build environment, and have the Java code use that variable at compile time to switch which line of code gets built. Unfortunately I've not been able to figure out how to do that.
I'd need a functionality similar to the following pseudo code
#ifdef $(VisualStudio)
LoadLibrary("libVS.so");
#elif $(AndroidStudio)
LoadLibrary("libAS.so");
#endif
Is this actually possible? Are there other/better ways to achieve my goal?
Upvotes: 2
Views: 789
Reputation: 17372
I'm not familiar with building java Android apps in visual studio, but with Gradle in android studio you would probably solve such a requirement with different build variants. So I suppose this should be possible with VS and Gradle too.
One possibility would be to define a Environment
class to hold the name of the library ( and possibly other values too)
public final class Environment {
public static final String LIBRARY= "libAS.so";
}
Then in your class you load the library by the given name
LoadLibrary (Environment.LIBRARY);
Then you can add another build variant for your vs code build. With different build variants you can have different versions of a file used during the build. Just create a subfolder for the variants and create a different Environment
class, holding the correct filename.
public final class Environment {
public static final String LIBRARY= "libVS.so";
}
Now depending on which variant you select to build, the respective Environment
class will be used and thus, the correct library will be loaded.
One drawback of this approach is, you may need to duplicate all your existing build variants. But on the other hand, you can have a single point, where you can put all your environment specific values and don't have to worry in different java files to use the correct values, because you don't have any conditional compiling.
Upvotes: 1