如何在Network Security Configuration文件中引用资源值以遵循DRY原则?
在Network Security Configuration中引用资源值的解决方案
直接在Network Security Configuration文件中使用@string/my_ip无法生效,因为该配置文件的解析逻辑不支持这类资源引用方式。以下两种方法可实现单一数据源,符合DRY原则:
方法1:Gradle动态替换(兼容所有Android版本)
这种方式通过Gradle在编译阶段完成配置文件的内容替换,同时同步给代码提供变量:
- 在Module级别的build.gradle中定义IP变量并生成对应资源:
android { defaultConfig { // 供代码直接调用的变量 buildConfigField "String", "MY_IP", "\"123.123.123.123\"" // 生成字符串资源,用于配置文件替换 resValue "string", "my_ip", "123.123.123.123" } }
- 修改
network_security_config.xml,将IP替换为占位符:
<network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">${my_ip}</domain> </domain-config> </network-security-config>
- 在build.gradle中添加编译时替换规则:
android { applicationVariants.all { variant -> variant.mergeResources.doLast { File xmlFile = file("${outputDir}/res/xml/network_security_config.xml") if (xmlFile.exists()) { String content = xmlFile.getText('UTF-8') content = content.replace("${my_ip}", variant.resValue.getString("my_ip")) xmlFile.write(content, 'UTF-8') } } } }
编译时Gradle会自动将占位符替换为实际IP,代码中可通过BuildConfig.MY_IP获取同一值,实现一处修改多处生效。
方法2:API 30+直接引用资源(仅适用于Android 11及以上)
若应用的minSdkVersion≥30,可直接在配置文件中引用字符串资源:
- 在
res/values/strings.xml中定义IP:
<string name="my_ip">123.123.123.123</string>
- 修改
network_security_config.xml:
<network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">@string/my_ip</domain> </domain-config> </network-security-config>
代码中通过getString(R.string.my_ip)获取该值,即可统一维护IP地址。
注:之前尝试@string/my_ip未成功,大概率是应用的minSdkVersion低于30,此时只能采用方法1解决。
内容的提问来源于stack exchange,提问作者Ernesto David Oliva Perez
相关产品推荐
相关产品推荐

