我希望在Android的ant release和debug构建过程中,使用不同的字符串资源文件。这是为了拥有地图API密钥、远程主机等不同的配置。
我日常使用Eclipse进行Debug构建,然后使用Ant进行发布构建。我有包含Google Maps API密钥的文件的Debug和Release版本。我修改了build.xml(我使用的是SDK Tools R15),在构建之前和之后执行一些复制适当文件的操作。我已将-pre-build和release目标更改如下:
<target name="-pre-build">
<echo message="In pre build-----------------------------------" />
<echo message="build target ${build.target}" />
<if condition="${build.is.packaging.debug}">
<then>
<echo>Copying debug api key************************************</echo>
<copy file="${layout.dir}/googlemapdebug.xml" tofile="${layout.dir}/googlemap.xml" overwrite="true" />
</then>
<else>
<echo>Copying RELEASE api key************************************</echo>
<copy file="${layout.dir}/googlemaprelease.xml" tofile="${layout.dir}/googlemap.xml" overwrite="true" />
</else>
</if>
</target>
<target name="release"
depends="clean, -set-release-mode, -release-obfuscation-check, -package, -release-prompt-for-password, -release-nosign"
............. LINES OMITTED
.............
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.file}"
out.package="${out.final.file}" />
<echo>Release Package: ${out.final.file}</echo>
<echo>Always copy DEBUG MAPS API file back for Eclipse **********************</echo>
<copy file="${layout.dir}/googlemapdebug.xml" tofile="${layout.dir}/googlemap.xml" overwrite="true" />
</sequential>
</do-only-if-not-library>
<record-build-info />
</target>
我在ant.properties(SDK Tools 14后build.properties的新名称)文件中定义了layout.dir:
projectname=MyProject
workspace.dir=/dev/projects/EclipseIndigo/AndroidWorkTwo
base.dir=${workspace.dir}/${projectname}
layout.dir=${base.dir}/res/layout
<target name="-pre-build">
<if condition="${build.is.packaging.debug}">
<then>
<echo>Copying debug config</echo>
<copy file="./config/debug.xml" tofile="./res/values/config.xml" overwrite="true"/>
</then>
<else>
<echo>Copying release config</echo>
<copy file="./config/release.xml" tofile="./res/values/config.xml" overwrite="true"/>
</else>
</if>
</target>
以下两个答案都基于Eclipse ADT
。现在,Android Studio
是更受欢迎的IDE,您可以利用gradle
构建系统。
在您的build.gradle
文件中,在android
标签中添加以下代码:
buildTypes {
release {
buildConfigField "boolean", "LOG_DEBUG", "false"
resValue "string", "some_key", "AAAAAAA"
}
debug {
buildConfigField "boolean", "LOG_DEBUG", "true"
resValue "string", "some_key", "BBBBBBB"
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(".apk", "-" + defaultConfig.versionName + ".apk"))
}
}
}
}
在您的Java代码中,可以将BuildConfig.LOG_DEBUG
用作boolean
值。只需记得import your.package.name.BuildConfig;
您还可以将some_key
用作字符串资源。使用它的Java代码是:R.string.some_key
。
release.preferences.xml
和 debug.preferences.xml
。 - Paweł Szczur