4

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.

Jonik
  • 80,077
  • 70
  • 264
  • 372
Bart
  • 301
  • 5
  • 12

2 Answers2

11

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.

flx
  • 14,146
  • 11
  • 55
  • 70
  • hehe i just run AndroidStudio to find the same solution in my code :) but i'm using `productFlavors` – Selvin Sep 12 '13 at 14:51
  • 6
    In later versions of Gradle / Android Gradle plugin, you must use `buildConfigField` (instead of `buildConfig`) as [described in this answer](http://stackoverflow.com/a/20678232/56285). – Jonik Jan 21 '14 at 09:10
7

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
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159