"Android Development Experience" complete guide to using Ant 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 the whole 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 sense of writing is not specific.

What's more important is that. The differences between the various methods are relatively large. For beginners. The choice between the various methods is extremely painful, a way to experiment with a method is a very waste of time.

Therefore, I would like to provide you with a complete, specific ant packaging Android app tutorial, easy to learn and future reference.

Don't say much nonsense. Start the commentary.

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. Now the latest version number is: Ant 1.9.4.

Why use ant to pack Android apps in bulk: When we publish the app, we may need to send it to more than 10. Even dozens of different distribution channels. For example, 360 mobile phone market, application package, wood ant market and so on, we may need to download the various channels such as data analysis, such as the use of Baidu mobile statistics and so on. To achieve statistical functionality, we need to include an element in the configuration file to identify which channel our app is going to be published to. Therefore, if we use the traditional method, we publish the version number of each channel. You need to change the data elements in the manifest file, and then use KeyStore to sign and package.

If there are only one or two channels of distribution. The workload is acceptable, but if our distribution channel hits dozens of. We assume that the changes are made manually and then signed and packaged for publication. The workload is very considerable. So, to address this need, we use ant to implement our own active packaging for Android applications.

After applying the background statement, we officially started.

1. Configure Java Environment variables

Although today's JDK version number version number does not need to be manually configured environment variables can also be performed normally, but in order to prevent the occurrence of unknown errors. Or configure it, detailed how to configure. Baidu under it.

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 my, as seen below

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">

3. Configuring the ANT Environment

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

I'm using the apache-ant-1.7.1 version number, unzip it, and unzip it to a directory, for example, my E:\apache-ant-1.7.1

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">


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

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">


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

After the configuration is complete. Open the Dos form and enter the command ant, if you see it as shown below. The configuration succeeds



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

After the environment variable is configured. We'll be able to start testing. First, we set up a test project, named Project, and the folder structure, for example, I just created a simple project. Nothing's Moving!



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

Open the DOS command form, use the cd/d path command, reach the root folder of our project, and then use Android Update Project--path. command, create our Build.xml file below the current folder. My execution steps are as follows. You can change the folder according to your actual situation. Be careful not to forget the back.



Once created, we refresh project, then. Today's folder structure, such as the one seen below

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">


After that. Our Build.xml file is created.

5. Create and change configuration files

After you finish creating the Build.xml file. We first add a data element in the Androidmanifest.xml file, the code for example


The following Name property differs depending on the platform. We're going to do that. is to replace the previous value and implement the package

After the change, we copied the manifest file and renamed it AndroidManifest.xml.temp. Then change the contents of the AndroidManifest.xml.temp file and replace the data source with our replacement. For example, the following can be seen

<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 named ant.properties . There is no need to add anything temporarily.

After this step is over. The structure of your file should be this.



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

Suppose we want to publish our application, we definitely need a signed key. Start by using Android tools to create a keystore. The details of how to create I will not say. Baidu Bar



Once created, save in a location, for example. My in the D packing folder below.

After these are all finished. We need to make changes to the configuration file.

First of all. Open our Build.xml file. Change the project property to the name of the item we want to package, for example, here we are project



After the change. Save. Then open the Ant.properties file. Fill in the following content

Represents keystore save path, password, alias, alias Password, save after change

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

7. Configure your own Active Packager

So far, we have finished the configuration information on the Android side. Following. We're about to finish. Ant's Own active packaging program has been written

First of all. Ant has its own active wrapper program structure, such as the one seen below



We create a pure javaproject and 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 unzip folder. My E:\apache-ant-1.7.1\lib, for example.

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

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">

a while. The program will traverse the string in one line. After you have replaced the appropriate location, pack the appropriate APK installation package.

8. Complete Ant's Own active packaging program

Now that we're ready, we'll be able to start the ant wrapper, and I'll write the code in the following, where I need to make a change, and I've been staring.

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's Own Active Packager * @author: Zhaokaiqiang * @tim e:2014-7-24 pm 5:47:04 * @version: V1.0 */public class Anttest {private Project project;private final static String project BasePath = "G:\\workspace\\project";//the project root folder to be packaged private final static String Copyapkpath = "g:\\";// Save the root folder of the packaged apk private final static String signapk = "project-release.apk";//the file name here must be the exact project name! is the name of the APK installation package under the Bin folder 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 (Placeholder) @SuppressWarnings ("resource") public that requires a change to the manifest file 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 Bulk Self-starter 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) {//Change manifest file First: Read @[email protected in temporary file] change 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 ()));//Run the package command anttest mytest = new Anttest (); Mytest.init (Projectbasepath + file.separator + "Build.xml", Projectbasepath ); Mytest.runtarget ("clean"); Mytest.runtarget ("release");//Run rename and copy operation after package file = new file (pRojectbasepath + file.separator + "bin" + File.separator + signapk);///Bin folder signed apk file filename renamefile = new file (copyapkpat H + file.separator+ renameapk + flag + ". apk");//Move the packaged apk to the Copyapkpath location by renaming the Boolean Renametag = File.renameto (renamefil e); SYSTEM.OUT.PRINTLN ("rename------>" + renametag); SYSTEM.OUT.PRINTLN ("file------>" + file.getabsolutepath ()); SYSTEM.OUT.PRINTLN ("rename------>" + renamefile.getabsolutepath ());} System.out.println ("---------ant bulk Self-active packaging end----------"); endTime = System.currenttimemillis (); Date.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----------in---------ant bulk self-active 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 back * * @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 from file path br = new BufferedReader (new FileReader (FilePath));//loop read each file Row, make changes to the row that needs to be changed, put in the buffer object while (line = Br.readline ()) = null) {//Here according to the actual need to change the contents of some rows 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) {Buffere Dwriter bw = null;try {//create buffered output stream from file path bw = new BufferedWriter (new FileWriter (FilePath));//write contents to file Bw.write (content);} C Atch (Exception e) {e.printstacktrace ();} finally {//close stream if (bw! = NULL) {try {bw.close ()} catch (IOException e) {bw = Nu ll;}}}}

Here's where everyone needs to change.



What might go wrong is the value of signapk. In general, our project name is the time of project. The name of the package should also be project.apk. However, when using ant for Packaging, a-release suffix is added later, so we still need to write this project-release.apk

Assuming we set this property incorrectly, we can't get our apk file at the target location we set.

9. After that, we will be able to execute our anttest program and package it. Assuming the results of execution and I are almost the same, then congratulations, packaging Success!



Then we come to our target directory. We can see. Packaged apk file. Has lain quietly here.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvemhhb2thaxfpyw5nmtk5mg==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/center ">


10. Verify that the replacement is successful

After getting our installation package, we were able to decompile our project in order to verify that the replacement was implemented in the manifest file. I am using the GUI interface of the Anti-compilation tool apktool_gui_1.3.5

Easy to use


Following. We open the manifest file. See if the corresponding data element has changed.



Did become the string we configured.

If it occurs when executed

Perhaps Java_home does not point to the JDK error

Set Eclipse Menu –window–preferences–java–installed jres– The JRE entry in the selected column table –edit–add External jars– Select the JDK folder/lib/tools . Jar-Confirm that it adds JRE system Libraries–finish–ok

So far. This concludes with a tutorial on using ant to Bulk pack Android, which has been written for two hours. So tired.


The demo sample code and tools in the article:

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


"Android Development Experience" complete guide to using Ant bulk pack Android Apps

Related Article

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.