Skip to content

Instantly share code, notes, and snippets.

@tangzhen
Forked from dominicbartl/ServerUtil.java
Last active November 16, 2015 14:12
Show Gist options
  • Save tangzhen/864355425b499a485a76 to your computer and use it in GitHub Desktop.
Save tangzhen/864355425b499a485a76 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