Using ant to implement bulk packaging Android applications

Source: Internet
Author: User
Tags readline stringbuffer

The main story is how to automatically build tools ant, batch packaging of applications to generate applications corresponding to different markets:

First take a look at the Java Engineering anttest for packaging and the Android architecture that needs to be packaged for release : market.txt to store the market markings that need to be packaged, such as: Youmeng Gfan .....   In this file, you add the channel name to your needs. Then look at the implementation of the bulk packaging Anttest class content:

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;

	public class Anttest {private Project project;

		public void init (string _buildfile, String _basedir) throws Exception {Project = new project ();

		Project.init ();
		Defaultlogger Consolelogger = new Defaultlogger ();
		Consolelogger.seterrorprintstream (System.err);
		Consolelogger.setoutputprintstream (System.out);
		Consolelogger.setmessageoutputlevel (Project.msg_info);

		Project.addbuildlistener (Consolelogger); Set the base directory.
		If none is given, '. ' is used.

		if (_basedir = = null) _basedir = new String (".");

		Project.setbasedir (_basedir); if (_buildfile = = null) _buildfile = new String (pRojectbasepath + file.separator + "Build.xml");
		Projecthelper.getprojecthelper (). Parse (project, new//File (_buildfile)); <span style= "color: #FF0000;"
	>//Key Code </span> projecthelper.configureproject (Project, New File (_buildfile)); } public void Runtarget (String _target) throws Exception {//Test if the project exists if (project = null) THR ow new Exception ("No target can be launched because the project has not been."
		Please call the ' init ' method:
		If no target is specified, run the default one.

		if (_target = = null) _target = Project.getdefaulttarget ();

	Run the target project.executetarget (_target); } <span style= "color: #FF0000;" >private final static string projectbasepath = "d:androidworkspace3xxx";//the project root to be packaged private final static string Copya
	Pkpath = "d:androidapktest";//Save package APK root private final static String signapk = "xxx-release.apk";//the filename here must be the exact project name! Private final static String ReNameapk = "xxx_";//renamed project name prefix (map item not to be changed) private final static String placeholder = "@market @";/Where you need to modify manifest file (placeholder) <
		/SPAN> 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 bulk Automation packaging start----------");
			StartTime = System.currenttimemillis ();
			Date.settimeinmillis (starttime);

			System.out.println ("Start time is:" + Sdf.format (Date.gettime ()));
			BufferedReader br = new BufferedReader (New FileReader ("Market.txt"));
			String flag = null; while ((flag = Br.readline ())!= null) {//First modify manifest file: Read @market@ in temporary file to market identity, then write to Manifest.xml String TEMPFI
				Lepath = Projectbasepath + file.separator + "AndroidManifest.xml.temp";
				String FilePath = projectbasepath + file.separator + "Androidmanifest.xml";
	Write (FilePath, read (TempFilePath, Flag.trim ()));			Execute Package Command Anttest mytest = new Anttest ();
				Mytest.init (Projectbasepath + file.separator + "Build.xml", Projectbasepath);
				Mytest.runtarget ("clean");
				Mytest.runtarget ("release"); Perform a rename and copy operation after the package is finished (file = new file (Projectbasepath + file.separator + "bin" + File.separator + signapk);/b
				The signed APK file in the directory renamefile = new file (Copyapkpath + file.separator + renameapk + flag + ". apk");
				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 bulk Automation 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 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)); }/** * Based on the number of seconds, calculates the difference time and returns * * * @param d1 * @param * * @return * D2 * in * * (*) (* *) (* *) (* * *) Getbeapa
		Rtdate (long m) {m = m/1000;
		String beapartdate = "";
		int nday = (int) m/(24 * 60 * 60);
		int nhour = (int) (M-nday * 24 * 60 * 60)/(60 * 60);
		int nminute = (int) (M-nday * 60-nhour * 60 * 60)/60;
		int nsecond = (int) m-nday * 60-nhour * 60-nminute * 60;

		Beapartdate = Nday + "Days" + Nhour + "hours" + nminute + "min" + nsecond + "seconds";
	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)); Iterates through each row of the file, modifies the rows that need to be modified, and puts them in the buffered object while (line = Br.readline ())!= null) {//Here Modify the contents of some rows according to the actual needs if (Line.conta
					INS (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 {//close stream if (br!= null) {try {br.close ();
				catch (IOException e) {br = NULL;
	}} return buf.tostring (); /** * Writes the content back to the file * * @param filePath * @param content/public static void Write (string filePath, String C

		ontent) {BufferedWriter bw = null;
			try {//create buffered output stream from file path bw = new BufferedWriter (new FileWriter (FilePath));
		Writes the content to the file Bw.write (content);
		catch (Exception e) {e.printstacktrace (); Finally {//close stream if (BW!= null)
				{try {bw.close ();
				catch (IOException e) {bw = NULL; }
			}
		}
	}
}

Then there is the part of the Android project that needs to be modified:

1. Modify the SDK root directory in Local.properties:
Sdk.dir=d:androidandroid-sdk-windows-r17android-sdk-windows-r17
2. Modify the path and password of the signed file in Ant.properties (if required)
Key.store=d:androidmykeystore
key.store.password=123456
Key.alias=mykey
key.alias.password=123456
3. Modify AndroidManifest.xml.temp
Copy androidmanifest.xml, named AndroidManifest.xml.temp
Change the place you want to replace to a placeholder, consistent with the placeholder constant in the package engineering Anttest
such as: <meta-data android:value= "@market @ " android:name= "Umeng_channel"/>
4. In Build.xml:
<project name= "XXX" default= "help" >,xxx must be the Android project name.

If the machine does not have an ant environment variable configured, you can configure it according to the following steps:

Ant environment variable settings:

There are 2 main environment variables used by Windows ANT, Ant_home, PATH.

Set the ant_home to point to Ant's installation directory.

To set the method:
Ant_home = d:/apache_ant_1.7.0

Will%ant_home%/bin; %ant_home%/lib is added to the path of the environment variable.

Set Method:
PATH =%ant_home%/bin;%ant_home%/lib

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.