Maven和android - 针对不同环境的略有不同的构建

时间:2012-12-13 19:40:00

标签: android maven ant

好的我正在安装一个android项目从ant切换到maven,并想知道以下是否易于实现:

目前我有一个自定义build.xml脚本,它有几个用于创建发布版本的目标。它们中的每一个都用于构建应用程序以针对不同的服务器URL运行,其中服务器可以是开发,生产,登台,甚至是我们在其他国家/地区的部署服务器。

原因是我们的应用程序将针对几个不同的服务器运行,具体取决于谁获取它,我不希望它是用户选择的东西。相反,它应该硬编码到应用程序中,这是它当前的工作方式。

这很容易在ant中设置,我只是从[env] .properties文件中取值,然后在res / values / config.xml中替换server_url字符串。例如:

ant release-prod

将读取名为prod.properties的文件,该文件定义server_url是什么。我将config.xml文件存储在config / config.xml中,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <string name="config_server_url">@CONFIG.SERVER_URL@</string>
</resources>

然后我的蚂蚁脚本会这样做:

<copy file="config/config.xml" todir="res/values" overwrite="true" encoding="utf-8">
    <filterset>
           <filter token="CONFIG.SERVER_URL" value="${config.server_url}" />
    </filterset>
</copy>

在prod.properties中定义了config.server_url。

我想知道如何用Maven完成类似的事情?有任何想法吗。我查看了如何使用maven读取属性文件,看起来结果是混合的,无论这是否有效。

1 个答案:

答案 0 :(得分:5)

在Maven中,这称为资源过滤,android-maven-plugin支持过滤以下资源类型:

示例res / value / config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="config_server_url">${config.server.url}</string>
</resources>

用于过滤res /目录下所有xml文件的pom配置示例:

<build>
  <resources>
    <resource>
      <directory>${project.basedir}/res</directory>
      <filtering>true</filtering>
      <targetPath>${project.build.directory}/filtered-res</targetPath>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
  </resources>
  <plugins>
    <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <executions>
        <execution>
          <phase>initialize</phase>
          <goals>
            <goal>resources</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <groupId>com.jayway.maven.plugins.android.generation2</groupId>
      <artifactId>android-maven-plugin</artifactId>
      <extensions>true</extensions>
      <configuration>
        <sdk>
          <platform>10</platform>
        </sdk>
        <undeployBeforeDeploy>true</undeployBeforeDeploy>
        <resourceDirectory>${project.build.directory}/filtered-res</resourceDirectory>
      </configuration>
    </plugin>
  </plugins>
</build>

有几种方法可以定义替换值,您可以使用properties-maven-plugin在外部属性文件中定义它们。为简单起见,我更喜欢使用Maven配置文件并在pom.xml中定义它们,如下所示:

<profiles>
  <profile>
    <id>dev</id>
    <properties>
      <config.server.url>dev.company.com</config.server.url>
    </properties>
  </profile>
  <profile>
    <id>Test</id>
    <properties>
      <config.server.url>test.company.com</config.server.url>
    </properties>
  </profile>
  <profile>
    <id>Prod</id>
    <properties>
      <config.server.url>prod.company.com</config.server.url>
    </properties>
  </profile>
</profiles>

然后使用mvn clean install -Pxxx构建相应的apk。