使用 Ant 实现批量打包Android应用

由于公司运维需要以及应用中需要加上应用推广的统计,往往要对应二三十个渠道,按照正常方法一个一个的去生成不同渠道包的应用,不仅浪费了时间,而且大大降低了效率.

上一篇讲到使用Ant进行Zip/Tar包的解压缩,实际上Ant工具不仅仅具有此类功能,它更强大的地方在于自动化调用程序完成项目的编译,打包,测试等. 类似于C语言中的make脚本完成这些工作的批处理任务. 不同于MakeFile的是,Ant是纯Java编写的,因此具有很好的跨平台性.


在此我主要讲下如何自动构建工具Ant, 对应用进行批量打包, 生成对应不同市场的应用:


首先分别看一下用于打包的Java工程AntTest和需要被打包进行发布的Android工程结构:




market.txt里保存需要打包的市场标识,如:

youmeng

gfan

.......

此文件里自行根据需求添加渠道名称.


然后看一下实现批量打包AntTest类中的内容:

注意:红色标注部分需要进行修改:



  1. package com.cn.ant;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileReader;  
  7. import java.io.FileWriter;  
  8. import java.io.IOException;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Calendar;  
  11.   
  12. import org.apache.tools.ant.DefaultLogger;  
  13. import org.apache.tools.ant.Project;  
  14. import org.apache.tools.ant.ProjectHelper;  
  15.   
  16. public class AntTest {  
  17.     private Project project;  
  18.   
  19.     public void init(String _buildFile, String _baseDir) throws Exception {  
  20.         project = new Project();  
  21.   
  22.         project.init();  
  23.   
  24.         DefaultLogger consoleLogger = new DefaultLogger();  
  25.         consoleLogger.setErrorPrintStream(System.err);  
  26.         consoleLogger.setOutputPrintStream(System.out);  
  27.         consoleLogger.setMessageOutputLevel(Project.MSG_INFO);  
  28.         project.addBuildListener(consoleLogger);  
  29.   
  30.         // Set the base directory. If none is given, "." is used.  
  31.         if (_baseDir == null)  
  32.             _baseDir = new String(".");  
  33.   
  34.         project.setBasedir(_baseDir);  
  35.   
  36.         if (_buildFile == null)  
  37.             _buildFile = new String(projectBasePath + File.separator  
  38.                     + "build.xml");  
  39.   
  40.         // ProjectHelper.getProjectHelper().parse(project, new  
  41.         // File(_buildFile));  
  42.         <span style="color:#FF0000;">// 关键代码</span>  
  43.         ProjectHelper.configureProject(project, new File(_buildFile));  
  44.     }  
  45.   
  46.     public void runTarget(String _target) throws Exception {  
  47.         // Test if the project exists  
  48.         if (project == null)  
  49.             throw new Exception(  
  50.                     "No target can be launched because the project has not been initialized. Please call the 'init' method first !");  
  51.         // If no target is specified, run the default one.  
  52.         if (_target == null)  
  53.             _target = project.getDefaultTarget();  
  54.   
  55.         // Run the target  
  56.         project.executeTarget(_target);  
  57.   
  58.     }  
  59.   
  60.     <span style="color:#FF0000;">private final static String projectBasePath = "D:\\android\\workspace3\\XXX";//要打包的项目根目录  
  61.     private final static String copyApkPath = "D:\\android\\apktest";//保存打包apk的根目录  
  62.     private final static String signApk = "XXX-release.apk";//这里的文件名必须是准确的项目名!  
  63.     private final static String reNameApk = "XXX_";//重命名的项目名称前缀(地图项目不用改)  
  64.     private final static String placeHolder = "@market@";//需要修改manifest文件的地方(占位符)  
  65. </span>  
  66.     public static void main(String args[]) {  
  67.         long startTime = 0L;  
  68.         long endTime = 0L;  
  69.         long totalTime = 0L;  
  70.         Calendar date = Calendar.getInstance();  
  71.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");  
  72.         try {  
  73.             System.out.println("---------ant批量自动化打包开始----------");  
  74.             startTime = System.currentTimeMillis();  
  75.             date.setTimeInMillis(startTime);  
  76.             System.out.println("开始时间为:" + sdf.format(date.getTime()));  
  77.   
  78.             BufferedReader br = new BufferedReader(new FileReader("market.txt"));  
  79.             String flag = null;  
  80.             while ((flag = br.readLine()) != null) {  
  81.   
  82.                 // 先修改manifest文件:读取临时文件中的@market@修改为市场标识,然后写入manifest.xml中  
  83.                 String tempFilePath = projectBasePath + File.separator  
  84.                         + "AndroidManifest.xml.temp";  
  85.                 String filePath = projectBasePath + File.separator  
  86.                         + "AndroidManifest.xml";  
  87.                 write(filePath, read(tempFilePath, flag.trim()));  
  88.                 // 执行打包命令  
  89.                 AntTest mytest = new AntTest();  
  90.                 mytest.init(projectBasePath + File.separator + "build.xml",  
  91.                         projectBasePath);  
  92.                 mytest.runTarget("clean");  
  93.                 mytest.runTarget("release");  
  94.                 // 打完包后执行重命名加拷贝操作  
  95.                 File file = new File(projectBasePath + File.separator + "bin"  
  96.                         + File.separator + signApk);// bin目录下签名的apk文件  
  97.                   
  98.                 File renameFile = new File(copyApkPath + File.separator + reNameApk  
  99.                         + flag + ".apk");  
  100.                 boolean renametag = file.renameTo(renameFile);  
  101.                 System.out.println("rename------>"+renametag);  
  102.                 System.out.println("file ------>"+file.getAbsolutePath());  
  103.                 System.out.println("rename------>"+renameFile.getAbsolutePath());  
  104.             }  
  105.             System.out.println("---------ant批量自动化打包结束----------");  
  106.             endTime = System.currentTimeMillis();  
  107.             date.setTimeInMillis(endTime);  
  108.             System.out.println("结束时间为:" + sdf.format(date.getTime()));  
  109.             totalTime = endTime - startTime;  
  110.             System.out.println("耗费时间为:" + getBeapartDate(totalTime));  
  111.   
  112.         } catch (Exception e) {  
  113.             e.printStackTrace();  
  114.             System.out.println("---------ant批量自动化打包中发生异常----------");  
  115.             endTime = System.currentTimeMillis();  
  116.             date.setTimeInMillis(endTime);  
  117.             System.out.println("发生异常时间为:" + sdf.format(date.getTime()));  
  118.             totalTime = endTime - startTime;  
  119.             System.out.println("耗费时间为:" + getBeapartDate(totalTime));  
  120.         }  
  121.     }  
  122.   
  123.     /** 
  124.      * 根据所秒数,计算相差的时间并以**时**分**秒返回 
  125.      *  
  126.      * @param d1 
  127.      * @param d2 
  128.      * @return 
  129.      */  
  130.     public static String getBeapartDate(long m) {  
  131.         m = m / 1000;  
  132.         String beapartdate = "";  
  133.         int nDay = (int) m / (24 * 60 * 60);  
  134.         int nHour = (int) (m - nDay * 24 * 60 * 60) / (60 * 60);  
  135.         int nMinute = (int) (m - nDay * 24 * 60 * 60 - nHour * 60 * 60) / 60;  
  136.         int nSecond = (int) m - nDay * 24 * 60 * 60 - nHour * 60 * 60 - nMinute  
  137.                 * 60;  
  138.         beapartdate = nDay + "天" + nHour + "小时" + nMinute + "分" + nSecond + "秒";  
  139.   
  140.         return beapartdate;  
  141.     }  
  142.   
  143.     public static String read(String filePath, String replaceStr) {  
  144.         BufferedReader br = null;  
  145.         String line = null;  
  146.         StringBuffer buf = new StringBuffer();  
  147.   
  148.         try {  
  149.             // 根据文件路径创建缓冲输入流  
  150.             br = new BufferedReader(new FileReader(filePath));  
  151.   
  152.             // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中  
  153.             while ((line = br.readLine()) != null) {  
  154.                 // 此处根据实际需要修改某些行的内容  
  155.                 if (line.contains(placeHolder)) {  
  156.                     line = line.replace(placeHolder, replaceStr);  
  157.                     buf.append(line);  
  158.                 } else {  
  159.                     buf.append(line);  
  160.                 }  
  161.                 buf.append(System.getProperty("line.separator"));  
  162.             }  
  163.         } catch (Exception e) {  
  164.             e.printStackTrace();  
  165.         } finally {  
  166.             // 关闭流  
  167.             if (br != null) {  
  168.                 try {  
  169.                     br.close();  
  170.                 } catch (IOException e) {  
  171.                     br = null;  
  172.                 }  
  173.             }  
  174.         }  
  175.   
  176.         return buf.toString();  
  177.     }  
  178.   
  179.     /** 
  180.      * 将内容回写到文件中 
  181.      *  
  182.      * @param filePath 
  183.      * @param content 
  184.      */  
  185.     public static void write(String filePath, String content) {  
  186.         BufferedWriter bw = null;  
  187.   
  188.         try {  
  189.             // 根据文件路径创建缓冲输出流  
  190.             bw = new BufferedWriter(new FileWriter(filePath));  
  191.             // 将内容写入文件中  
  192.             bw.write(content);  
  193.         } catch (Exception e) {  
  194.             e.printStackTrace();  
  195.         } finally {  
  196.             // 关闭流  
  197.             if (bw != null) {  
  198.                 try {  
  199.                     bw.close();  
  200.                 } catch (IOException e) {  
  201.                     bw = null;  
  202.                 }  
  203.             }  
  204.         }  
  205.     }  
  206. }  


然后是Android工程中需要进行修改的部分:


1. 修改local.properties中的sdk根目录:

    sdk.dir=D:\\android\\android-sdk-windows-r17\\android-sdk-windows-r17

2. 修改ant.properties中签名文件的路径和密码(如果需要)
    key.store=D:\\android\\mykeystore
    key.store.password=123456
    key.alias=mykey
    key.alias.password=123456

3. 修改AndroidManifest.xml.temp
    拷贝AndroidManifest.xml一份,命名为AndroidManifest.xml.temp
    将需要替换的地方改为占位符,需与打包工程AntTest中的placeHolder常量一致

  如: <meta-data android:value="@market@" android:name="UMENG_CHANNEL"/>

4. Build.xml中:

    <project name="XXX" default="help">,XXX必须为Android工程名称.


如果机器没有配置过Ant环境变量,可根据如下步骤进行配置:


ANT环境变量设置:

Windows下ANT用到的环境变量主要有2个,ANT_HOME 、PATH

设置ANT_HOME指向ant的安装目录。

设置方法:
ANT_HOME = D:/apache_ant_1.7.0

将%ANT_HOME%/bin; %ANT_HOME%/lib添加到环境变量的path中。

设置方法:
PATH = %ANT_HOME%/bin; %ANT_HOME%/lib

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值