Skip to content

Instantly share code, notes, and snippets.

@dominicbartl
Created September 30, 2014 16:30
Show Gist options
  • Save dominicbartl/3dd1f036ddea41f3c39f to your computer and use it in GitHub Desktop.
Save dominicbartl/3dd1f036ddea41f3c39f to your computer and use it in GitHub Desktop.
Inject dynamic host IP address in with Gradle
...
android {
defaultConfig {
minSdkVersion 14
targetSdkVersion 19
buildConfigField "String", "LOCAL_IP", '\"' + getLocalIp("eth0") + '\"'
}
}
// Get the ip address by interface name
def getLocalIp(String interfaceName) {
NetworkInterface iface = NetworkInterface.getByName(interfaceName);
for (InterfaceAddress address : iface.getInterfaceAddresses()) {
String ip = address.getAddress().getHostAddress()
if (ip.length() <= 15) {
return ip;
}
}
}
private static final String HOST_EMULATOR = "10.0.2.2";
private static final String HOST_PRODUCTION = "example.com";
public static String getHost() {
if (BuildConfig.DEBUG) {
return (Build.PRODUCT).contains("sdk") ? HOST_EMULATOR : BuildConfig.LOCAL_IP;
}
return HOST_PRODUCTION;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment