我开发了一款与服务器通信的Android应用。我有2台服务器。一个用于开发,另一个用于生产。
在我的Android源代码中,我必须在构建时手动更改服务器网址。
例如: 对于调试模式发布,我使用:
String url = "http://develop/service"
生产发布,我使用:
string url = "http://production/service"
url
变量传递给请求发送函数,如sendReqToServer(url);
。
我厌倦了针对不同版本对此网址更改进行手动更改。相反,我想使用 Ant脚本在进行不同的发布版本时使用命令行来指定url
,例如ant release-develop
(使用开发服务器)& ant release-product
(使用生产服务器)。
为实现这一目标,我认为在 build.xml 中我需要创建<target name="release-develop">
&amp; <target name="release-product">
。但我不知道如何让ant脚本通过命令行指定我的应用程序的URL?
有人可以向我提供有关如何操作的更详细信息吗?
答案 0 :(得分:2)
您可以使用replace
任务覆盖/替换网址。它看起来像这样:
<target name="release-product">
<replace file="path to your *.java class which contains url" token="@URL@" value="http://production/service">
<!-- compile app -->
</target>
<target name="release-develop">
<replace file="path to your *.java class which contains url" token="@URL@" value="http://develop/service">
<!-- compile app -->
</target>
这不是最佳解决方案,因为您需要更改源代码。最好是创建配置文件,您将从中读取URL。在这种情况下,它将如下所示:
YourUrlClass.java
String url = Config.getUrl(); // get Url method will read url from config file
Appconfig.ini
url=http://develop/service
的build.xml
<target name="release-product">
<echo file="appconfig.ini" override="true">url=http://product/product</echo>
<!-- compile app using appconfig.ini -->
</target>
<target name="release-develop">
<echo file="appconfig.ini" override="true">url=http://develop/product</echo>
<!-- compile app using appconfig.ini -->
</target>
当然,您不需要使用<echo/>
任务创建appconfig.ini文件。我们的想法是您可以使用不同的版本覆盖appconfig.ini
文件。
答案 1 :(得分:0)
我会像其他答案一样使用配置文件,但这是我通常只记录开发版本的另一种可能性:
if( BuildConfig.DEBUG )
{
//set develop
}
else
{
//set release
}
此BuildConfig.DEBUG基于是否在调试或发布模式下编译而设置。
答案 2 :(得分:0)
您可以在需要服务器网址的所有目标中使用属性${url}
:
<target name="release">
<echo> Deployment => ${url} started !</echo>
...
</target>
并通过以下方式启动您的antfile:
ant -f yourfile.xml -Durl=http://develop/service
或
ant -f yourfile.xml -Durl=http://production/service
如果您有更多特定属性,请为每个deploytarget和antfile使用创建属性文件:
<property file="/config/${deploymode}.properties"/>
然后通过以下方式启动您的antfile:
ant -f yourfile.xml -Ddeploymode=test
或
ant -f yourfile.xml -Ddeploymode=production