Can I use Ant to set some static variables in my Android project when building?
I would like to automate my Android project building with Ant. Currently I have to change some static String and Boolean fields in one of the classes for different kind of versions of the same app for different markets.
Is it possible to set these variables with Ant, without resorting to copying a file with some strange markers in it? I want to be able to开发者_运维知识库 keep using the files in Eclipse.
You can, but you shouldn't. Don't make your Ant build file mess with the code; it leads to strange and confusing errors that are hard to find.
Instead, use java Properties.
Here's a little example of how a static final
can be initialized in a static
block:
class Junk {
public static final int j ;
static {
// Use java.lang.Properties here to get the values
j = 42;
}
public static void main(String[] argv){
System.out.printf("The answer is %d\n" , j);
}
}
Yes you can.
When copying, use a filterset. Include a few filter tokens to be replaced in the text file, and in the filterset specify the token and the value to replace it.
<copy todir="../backup/dir">
<fileset dir="src_dir"/>
<filterset>
<filter token="TITLE" value="Foo Bar"/>
</filterset>
</copy>
Note that you must do this prior to attempting to compile the file, so you might have to rework a bit of the compiling logic to be compatible with the filtered copy.
Personally, I make a build/processed-src directory and copy everything into it filtered (copy will only update out-of-date files) and then rework the compile chain to compile from there.
Possibly you can create a stub "java" file which is "echo"ed out as part of the ant build.
<echo file="com/corp/product/Version.java">
package com.corp.product;
public class Version {
public static final int MAJOR = ${version.major};
public static final int MINOR = ${version.minor};
public static final String full = "${version.major}-${version.minor}";
}
</echo>
It gets around most of the complaints about having to copy, but it does mean that the class will have to be maintained within the ant build file (or in an included ant build file).
精彩评论