-
-
Save tangzhen/864355425b499a485a76 to your computer and use it in GitHub Desktop.
Inject dynamic host IP address in with Gradle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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