Android 模拟器访问本地网络 - 是否可以在不更改代码的情况下将 127.0.0.1 映射到 10.0.2.2?
Android emulator access local network - Is it possible to map 127.0.0.1 to 10.0.2.2 without changing code?
在代码中,我有一些地方是字符串 127.0.0.1。我有没有办法告诉 Android 模拟器所有对 127.0.0.1 的调用都应该像对 10.0.2.2 的调用一样?
最好的方法是为正确的环境替换字符串。您可以将以下内容添加到应用 build.gradle
文件内的 android
标签中。
flavorDimensions "version"
productFlavors {
device {
buildConfigField "String", "BASE_WEB_URL", "127.0.0.1"
}
emulator {
buildConfigField "String", "BASE_WEB_URL", "10.0.2.2"
}
}
//comment this block if you want the emulatorRelease build variant (but you probably wont)
variantFilter { variant ->
def names = variant.flavors*.name
if (variant.buildType.name == "release" && names.contains("emulator")) {
// Gradle ignores any variants that satisfy the conditions above.
setIgnore(true)
}
}
这样您将拥有 3 个构建变体(您可以在 Android Studio 的左下面板更改构建变体)。根据您选择的构建变体,您将 BASE_WEB_URL
正确更新为正确的值。
在您的代码中,您只需将所有“127.0.0.1”和“10.0.2.2”替换为
BuildConfig.BASE_WEB_URL
在代码中,我有一些地方是字符串 127.0.0.1。我有没有办法告诉 Android 模拟器所有对 127.0.0.1 的调用都应该像对 10.0.2.2 的调用一样?
最好的方法是为正确的环境替换字符串。您可以将以下内容添加到应用 build.gradle
文件内的 android
标签中。
flavorDimensions "version"
productFlavors {
device {
buildConfigField "String", "BASE_WEB_URL", "127.0.0.1"
}
emulator {
buildConfigField "String", "BASE_WEB_URL", "10.0.2.2"
}
}
//comment this block if you want the emulatorRelease build variant (but you probably wont)
variantFilter { variant ->
def names = variant.flavors*.name
if (variant.buildType.name == "release" && names.contains("emulator")) {
// Gradle ignores any variants that satisfy the conditions above.
setIgnore(true)
}
}
这样您将拥有 3 个构建变体(您可以在 Android Studio 的左下面板更改构建变体)。根据您选择的构建变体,您将 BASE_WEB_URL
正确更新为正确的值。
在您的代码中,您只需将所有“127.0.0.1”和“10.0.2.2”替换为
BuildConfig.BASE_WEB_URL