1

我开发了一个与服务器通信的 Android 应用程序。我有 2 台服务器。一种用于开发,另一种用于生产

在我的 Android 源代码中,我必须在构建时手动更改服务器 URL 。

例如:对于调试模式 release,我使用:

String url = "http://develop/service"

对于生产版本,我使用:

string url = "http://production/service"

url变量被传递给请求发送函数,如sendReqToServer(url);.

我厌倦了手动更改此 url 更改为不同的版本。相反,我想使用Ant 脚本url在进行不同的发布构建时使用命令行来指定,例如ant release-develop(使用开发服务器)和ant release-product(使用生产服务器)。

为此,我认为在build.xml中我需要创建<target name="release-develop">& <target name="release-product">。但我不确定如何让 ant 脚本通过命令行为我的应用程序指定 url?

有人可以向我提供有关如何操作的更详细信息吗?

4

3 回答 3

2

您可以使用replace任务来覆盖/替换 url。它看起来像这样:

<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。在这种情况下,它将如下所示:

你的UrlClass.java

String url = Config.getUrl(); // get Url method will read url from config file

应用程序配置文件

url=http://develop/service

构建.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使用不同的版本覆盖文件。

于 2013-03-13T12:47:21.683 回答
0

${url}您可以在需要服务器 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

如果您有更具体的属性,请为每个部署目标创建一个属性文件,并在您的 antfile 中使用:

<property file="/config/${deploymode}.properties"/>

之后通过以下方式启动您的 antfile:

ant -f yourfile.xml -Ddeploymode=test

或者

ant -f yourfile.xml -Ddeploymode=production
于 2013-03-13T21:03:19.787 回答
0

我可能会像其他答案一样使用配置文件,但这是我通常只记录开发版本的另一种可能性:

if( BuildConfig.DEBUG  )
{
    //set develop
}
else
{
    //set release
}

这个 BuildConfig.DEBUG 是根据它是在调试还是发布模式下编译来设置的。

于 2013-03-13T13:02:40.753 回答