4

好的,我正在一个 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>

其中 config.server_url 是在 prod.properties 中定义的。

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

4

1 回答 1

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。

于 2012-12-13T20:54:09.567 回答