Full guide to using ant to bulk pack Android apps

Source: Internet
Author: User

This article was completed by Socks, blog address: http://blog.csdn.net/zhaokaiqiang1992

Reprint please explain!

Tossing an afternoon, Baidu had an afternoon, and finally realized the use of ant for Android application of bulk packaging, but also a matter of my mind. Although this part of the online tutorial also has, but the feeling is not written in detail. More importantly, the differences between the various methods are relatively large, for the novice, the choice between the various methods is extremely painful, a method of a method to experiment, is a waste of time. Therefore, I would like to provide you with a complete, detailed Ant pack Android app tutorial, easy to learn and later reference.

Don't say much nonsense, start to explain.

What ant is: Ant is a Java-based build tool. Theoretically, it is somewhat similar to make in (Unix) C, but without the bug of make. The current version is: Ant 1.9.4.

Why use ant to bulk pack Android apps: When we publish an app, we may need to send it to more than 10 or even dozens of different distribution channels, such as 360 mobile phone market, application package, wood ant market and so on, we may need to analyze the download volume of each channel, such as the use of Baidu mobile statistics and so on. To achieve statistical functionality, we need to add an element to the configuration file to identify which channel our app is to be published to, so if we use the traditional approach, we need to modify the elements in the manifest file for each release of the channel, and then use KeyStore to sign and package. If there are only one or two distribution channels, the workload is acceptable, but if our distribution channels hit dozens of, if we manually modify and then signed packaging and release, then the workload is considerable. Therefore, to address this need, we use ant to automate the packaging of Android apps.

After applying the background statement, we formally started.

1. Configure Java Environment variables

Although the JDK version of the current version does not need to manually configure the environment variable can also run normally, but, in order to prevent the unknown error, or configure it, specifically how to configure, Baidu down bar.

2. Configure the SDK environment variables for Android

In addition to the need for Java environment variables, we also need to configure the location of the Android SDK, the name is Android_home, the value is the location of your Android SDK, such as mine, as shown below

3. Configuring the ANT Environment

In this tutorial, we use our own configured ant, because I am using Android Developer Tools, no ant plugins, so we use our own configured ant.

I'm using the apache-ant-1.7.1 version, unzip it, and unzip it to a folder, like, my E:\apache-ant-1.7.1.



After extracting the files, we need to configure the environment variables.


Then, add in Path ;%ant_home%/bin;%ant_home%/lib;

After the configuration is complete, open the DOS window and enter the command ant, if shown below, the configuration succeeds



4. Create an instance project, and create a build.xml configuration file

Once we've configured the environment variables, we're ready to start testing. First, we set up a test project, called Project, the directory structure as follows, I just created a simple project, nothing moved OH



Once the project is created, we need to create our Build.xml file using the commands from Android

Open the DOS command window, use the cd/d path command, reach the root of our project, and then use Android Update Project--path. command, under the current directory to create our Build.xml file, I run the process as follows, everyone according to their actual situation to modify the directory can be, pay attention not to forget the back.



Once created, we refresh the project, and now the directory structure is as follows



After that, our Build.xml file is created.

5. Create and modify configuration files

After creating the Build.xml file, we first add an element in the Androidmanifest.xml file, the code is as follows


The following Name property differs depending on the platform, and what we want to do is replace the previous value and implement the package

After the modification, we copy the manifest file and rename it to AndroidManifest.xml.temp, then modify the contents of the AndroidManifest.xml.temp file and replace the data source with our replacement, as shown below

<meta-data android:value="@[email protected]" android:name= "Umeng_channel"/> In the following code, we will @[email Protected] Replace with our channel name

Once created, we are creating a file called ant.properties , and we don't need to add anything for the time being.

At the end of this step, your file structure should look like this.



6. Create the KeyStore key and modify the relevant property profile

If you want to publish our app, we definitely need a signed key, first use Android tools to create a keystore, how to create I said, Baidu Bar



After creation, save in a location, for example, my under the D packing directory.

When this is all done, we need to modify the configuration file.

First, open our Build.xml file, modify the project property to the name of the project we want to package, for example, we are here project



After modification, save. Then open the Ant.properties file and fill in the following content

Represents keystore save path, password, alias, alias password, save after modification

key.store=d:\\android.keystorekey.store.password=123456key.alias=android.keystorekey.alias.password=123456

7. Configure the Automatic Packager

So far, we've completed the configuration information for Android, and we're going to complete the ant Auto-Packager program.

First, the Ant Automatic Packager program structure looks like this



We create a pure Java project, then create the Lib folder and add two external import packages. These two external import packages can be found in the lib of our ant extract directory, for example, my E:\apache-ant-1.7.1\lib

Market.txt is a plain txt text that is written in a string that we want to replace, for example, what I write is


In a few minutes, the program will walk through the string in a row, replace it with the corresponding location, and then package the APK installation package.

8. Complete the Ant Automatic Packager program

Once this is ready, we can begin to write the Ant wrapper, and I'll write the code below, where I need to make the changes, and I've commented on it.

Package Com.cn.ant;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.File;import Java.io.filereader;import Java.io.filewriter;import Java.io.ioexception;import Java.text.SimpleDateFormat;import Java.util.calendar;import Org.apache.tools.ant.defaultlogger;import Org.apache.tools.ant.project;import  org.apache.tools.ant.projecthelper;/** * * @ClassName: Anttest * @Description: Ant Automatic Packager * @author: Zhaokaiqiang * @time: 2014-7-24 pm 5:47:04 * @version: V1.0 */public class Anttest {private Project project;private final static String Projectba Sepath = "G:\\workspace\\project";//the project root directory to be packaged private final static String Copyapkpath = "g:\\";//The root directory of the APK after the package is saved private F inal static String signapk = "project-release.apk";//the file name here must be the exact name of the project! is the name of the APK installation package under the Bin Directory of Project project the private final static String renameapk = "project_";//Rename the project name prefix (map item not changed) private final static String PlaceHolder = "@[email protected]";//place where the manifest file needs to be modified (placeholder) @SuppressWarnings ("resource") public Static VOID Main (String args[]) {Long StartTime = 0l;long EndTime = 0l;long totaltime = 0L; Calendar date = Calendar.getinstance (); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd:hh:mm:ss"); try {System.out.println ("--------- Ant Batch Automation package starts----------"); startTime = System.currenttimemillis ();d ate.settimeinmillis (startTime); System.out.println ("Start time:" + Sdf.format (Date.gettime ())); BufferedReader br = new BufferedReader (New FileReader ("Market.txt")); String flag = null;while (flag = br.readline ()) = null) {//Modify manifest file First: Read @[email protected in temp file] Modify to market identity, Then write manifest.xml in string tempfilepath = Projectbasepath + file.separator+ "AndroidManifest.xml.temp"; String FilePath = Projectbasepath + file.separator+ "Androidmanifest.xml"; write (FilePath, read (TempFilePath, Flag.trim ());//Execute packaging command anttest mytest = new Anttest (); Mytest.init (Projectbasepath + file.separator + "Build.xml", Projectbasepath ); Mytest.runtarget ("clean"); Mytest.runtarget ("release");//After the package is executed rename and copy operation file File = new file (projectbaSepath + file.separator + "bin" + File.separator + signapk);//bin directory signed apk file filename renamefile = new file (Copyapkpath + file). separator+ renameapk + flag + ". apk");//Move the packaged apk to the Copyapkpath location by renaming the Boolean Renametag = File.renameto (renamefile); SYSTEM.OUT.PRINTLN ("rename------>" + renametag); SYSTEM.OUT.PRINTLN ("file------>" + file.getabsolutepath ()); SYSTEM.OUT.PRINTLN ("rename------>" + renamefile.getabsolutepath ());} System.out.println ("---------ant batch Automation packaging End----------"), EndTime = System.currenttimemillis ();d Ate.settimeinmillis ( EndTime); System.out.println ("End time:" + Sdf.format (Date.gettime ())); totaltime = Endtime-starttime; System.out.println ("Time-consuming:" + getbeapartdate (TotalTime));} catch (Exception e) {e.printstacktrace (); System.out.println ("Exception----------occurred in---------ant batch Automation packaging"); endTime = System.currenttimemillis (); Date.settimeinmillis (EndTime); System.out.println ("Abnormal time is:" + Sdf.format (Date.gettime ())); totaltime = Endtime-starttime; System.out.println ("Time-consuming:" + getbeapartdate (totaltiMe));}} public void init (string _buildfile, String _basedir) throws Exception {Project = new project ();p roject.init ();D Efaultlogg Er consolelogger = new Defaultlogger (); Consolelogger.seterrorprintstream (System.err); Consolelogger.setoutputprintstream (System.out); Consolelogger.setmessageoutputlevel (Project.MSG_INFO); Project.addbuildlistener (Consolelogger); if (_basedir = = null) _basedir = new String ("."); Project.setbasedir (_basedir); if (_buildfile = = null) _buildfile = new String (Projectbasepath + file.separator+ " Build.xml "); Projecthelper.configureproject (Project, New File (_buildfile));}  public void Runtarget (String _target) throws Exception {if (project = null) throw new Exception ("No Target can be launched Because the project has not been initialized. Please call the ' init ' method first! '); if (_target = = null) _target = Project.getdefaulttarget ();p roject.executetarget (_target);} /** * Based on the number of seconds, calculate the time difference and * * * * * * * * seconds to return * * @param d1 * @param d2 * @return */public static String getbeapartdate (long m) {m = m/1000; String beapartdate = ""; int nday = (int) m/($ *), int nhour = (int) (m-nday * * *)/(*); int NM Inute = (int) (M-nday * $ * 60-nhour *)/60;int Nsecond = (int) m-nday * $ * 60-nhour * 60 * 60-nminute* 60;beapartdate = nday + "Day" + Nhour + "hour" + Nminute + "min" + Nsecond + "second"; return beapartdate;} public static string Read (string FilePath, String replacestr) {BufferedReader br = null; String line = null; StringBuffer buf = new StringBuffer (); try {//create buffered input stream based on file path BR = new BufferedReader (new FileReader (FilePath));//loop read each file Row, modify the row that needs to be modified, put in the buffer object while (line = Br.readline ()) = null) {//Here Modify the contents of some rows according to the actual need if (Line.contains (PlaceHolder)) {line = Line.replace (PlaceHolder, REPLACESTR); Buf.append (line);} else {buf.append (line);} Buf.append (System.getproperty ("Line.separator"));}} catch (Exception e) {e.printstacktrace ();} finally {if (BR! = null) {try {br.close ();} catch (IOException e) {br = null;} }}return buf.tostring ();} /** * Write content back to file * * @param filePath * @param content */public static void write (string filePath, string content) {Bufferedw Riter bw = null;try {//create buffered output stream based on file path bw = new BufferedWriter (new FileWriter (FilePath));//write content to file Bw.write (contents);} Cat CH (Exception e) {e.printstacktrace ();} finally {//close stream if (bw! = NULL) {try {bw.close ()} catch (IOException e) {bw = null ;}}}}}

Here's where everyone needs to be modified.



What might go wrong is the signapk value, which is generally the name of the package when our project name is Project project.apk. However, when using ant for Packaging, a-release suffix is added later, so we need to write this project-release.apk

If we set this property incorrectly, we will not be able to get our APK file at the target location we set.

9. After this, we can run our Anttest program, packaging, if the results of the operation and I have the following results, then congratulations, packaging Success!



Then we come to our target folder and we can see that the packaged APK file has been quietly lying here



10. Verify that the replacement is successful

After we get our installation package, in order to verify that we have implemented the replacement in the manifest file, we can decompile our project, and I am using the GUI Interface's anti-compilation tool apktool_gui_1.3.5

Very simple to use


Below, we open the manifest file to see if the corresponding data element has changed



Did become the string we configured.

If the run-time appears

Perhaps Java_home does not point to the JDK error

Set the Eclipse menu –window–preferences–java–installed jres– The JRE entry in the Selected columns table –edit–add External jars– Select the JDK directory/lib/tools. Jar-Confirm that it joins the JRE system Libraries–finish–ok

So far, the tutorial on using ant to bulk pack Android to this end, written for two hours, very tired ah.


Example code and tools in the article:

http://download.csdn.net/detail/bz419927089/7674043


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.