Search code examples
androidgradleemulationgenymotion

How to have Android Gradle build write a file that goes into the debug APK


GenyMotion's localhost IP address (10.0.3.2) is different from the Android emulator's localhost IP (10.0.2.2). Currently I have this in one of my source files:

//val LOCALHOST = "10.0.2.2"  // Android emulator
val LOCALHOST = "10.0.3.2"  // Genymotion

and whenever I switch between a Linux box and a Mac box and fetch the latest sources, I have to uncomment one and comment the other before rebuilding.

Unless someone can think of a better solution, I would like to have a Gradle task that writes out one of these values depending on the host OS, into a file that's included in the APK in such a way that I can access it from my Android app's runtime, and have that task run before assembleDebug when I build in Android Studio.

I suppose putting it in a resource would be easiest to access on the runtime side, but even a plain text file accessible to Class.getResourceAsStream() would be fine too.

I don't mind if it's included in the release apk, but I'd prefer that it just go into the debug ones.

I would also prefer that the file be generated in my build/ output directory, so that it's invisible to version control.

Any idea how to go about this?


Solution

  • There are much better solutions like finding the local IP address using getNetworkInterfaces(), but as you asked how to pass some information from gradle,

    android {
        productFlavors {
            flavorGenymotion {
                buildConfigField "String", "LOCALHOST", '"10.0.3.2"'
            }
            flavorEmulator {
                buildConfigField "String", "LOCALHOST", '"10.0.2.2"'
            }
        }
        ...
    

    which you can access as BuildConfig.LOCALHOST.