I am developing an app for Android that connects to my server. As usual my server during development is on a laptop and its ip is changing. I would like to detect ip address of my development machine i.e.
InetAddress.getLocalHost().getCanonicalHostName()
...and inject it into android strings.xml file so my Android app would connect to right ip during development.
I am struggling with determining where to get info what kind of buildType is run following part can be executed each time:
android { 
    buildTypes.each { buildType ->
        if(buildType.name == 'debug') {
            def host = InetAddress.getLocalHost().getCanonicalHostName()
        }
    }
}
Let's say that that host is determined right now. However I am still not sure how to replace host in strings.xml file in order to connect to the right host. I cannot call processResources as following exception is thrown:
Could not find method processResources() for argument [build_11onjivreh0vsff0acv5skf836$_run_closure3@cbbe2cf] on project
Any suggestion or source code would be appreciated.
There is an much easier solution available: Use a static final in BuildConfig:
buildTypes {
    debug {
        def host = InetAddress.getLocalHost().getCanonicalHostName()
        buildConfig "public static final String API_HOSTNAME = \"" + host + "\";"
    }
    release {
        buildConfig "public static final String API_HOSTNAME = \"whateveritisforreleasebuilds\";"
    }
}
BuildConfig.API_HOSTNAME will hold the remote address.
The following Syntax is required for the latest versions:
buildTypes {
    debug {
        buildConfigField "String", "ENVIRONMENT", "\"development\""
    }
    release {
        buildConfigField "String", "ENVIRONMENT", "\"production\""
    }
}
alternatively with a boolean type:
buildTypes {
    debug {
        buildConfigField "boolean", "ENVIRONMENT", "true"
    }
    release {
        buildConfigField "boolean", "ENVIRONMENT", "false"
    }
}
You would then use this as
BuildConfig.ENVIRONMENT.equals("production"); // String type
or
if (BuildConfig.ENVIRONMENT) { ... } // boolean type
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With