Using Ant to Automate Building Android Applications

UsingAnttoAutomateBuildingAndroidApplications

Step1:在命令行进入到需要打包项目目录。

Step2:androidupdateproject--path,这样在工程目录下会生成build.xml文件。

Hereisanexampleofsuccessfuloutput:

>androidupdateproject--path.

Updatedlocal.properties

AddedfileC:\dev\blog\antbuild\build.xml

Nowyouwillhaveaworkingantbuildscriptinbuild.xml.Youcantestyoursetupbytypingantatthecommandprompt,andyoushouldreceivesomethingsimilartothefollowingboilerplatehelp:

>ant

Buildfile:C:\dev\blog\antbuild\build.xml

[setup]AndroidSDKToolsRevision6

[setup]ProjectTarget:Android1.5

[setup]APIlevel:3

[setup]WARNING:NominSdkVersionvalueset.ApplicationwillinstallonallAndroidversions.

[setup]Importingrulesfile:platforms\android-3\ant\ant_rules_r2.xml

help:

[echo]AndroidAntBuild.Availabletargets:

[echo]help:Displaysthishelp.

[echo]clean:Removesoutputfilescreatedbyothertargets.

[echo]compile:Compilesproject's.javafilesinto.classfiles.

[echo]debug:Buildstheapplicationandsignsitwithadebugkey.

[echo]release:Buildstheapplication.Thegeneratedapkfilemustbe

[echo]signedbeforeitispublished.

[echo]install:Installs/reinstallsthedebugpackageontoarunning

[echo]emulatorordevice.

[echo]Iftheapplicationwaspreviouslyinstalled,the

[echo]signaturesmustmatch.

[echo]uninstall:Uninstallstheapplicationfromarunningemulatoror

[echo]device.

BUILDSUCCESSFUL

Iftheantcommandisnotfound,thenyouneedtoupdateyourpath.Likeabove,onWindowsusesetpath=%PATH%;C:\dev\apache-ant-1.8.1\bin(substitutingyouractualAntinstallationdirectory),orevenbetterupdateyourenvironmentvariables.

Atthispointyoushouldbeabletotypeantreleaseatthecommandprompt,whichwillbuildtheproject,placingtheunsigned.apkfileinsideofthebin/directory.

NotethattheoutputfromAntwillshowfurtherinstructionsunder-release-nosign:whichsaystosigntheapkmanuallyandtorunzipalign.We'llgettothesestepslaterinthesigningsectionbelow.

Creatinganewprojectwithbuild.xml

Ifyou'vealreadycreatedyourprojectandfollowedtheaboveinstructions,youcanskipthissection.Ifnot,youcanmayeithercreateanewAndroidprojectusingtheregularEclipsemethod(viaNew>Other...>AndroidProject),andfollowtheinstructionsintheabovesection,oryoucanusethecommandlineasdescribedhere.

androidcreateproject--nameYourProjectName--pathC:\dev\YourProject--targetandroid-3--packagecom.company.testproject--activityMainActivity

Hereisanexampleofsuccessfuloutput:

>androidcreateproject--nameYourTestProject--pathc:\temp\TestProject--targetandroid-3--packagecom.company.testproject--activityMainActivity

Createdprojectdirectory:c:\temp\TestProject

CreateddirectoryC:\temp\TestProject\src\com\company\testproject

Addedfilec:\temp\TestProject\src\com\company\testproject\MainActivity.java

CreateddirectoryC:\temp\TestProject\res

CreateddirectoryC:\temp\TestProject\bin

CreateddirectoryC:\temp\TestProject\libs

CreateddirectoryC:\temp\TestProject\res\values

Addedfilec:\temp\TestProject\res\values\strings.xml

CreateddirectoryC:\temp\TestProject\res\layout

Addedfilec:\temp\TestProject\res\layout\main.xml

Addedfilec:\temp\TestProject\AndroidManifest.xml

Addedfilec:\temp\TestProject\build.xml

Note:Toseetheavailabletargets,useandroidlisttargetandyoushouldseesomethinglike:

>androidlisttarget

id:1or"android-3"

Name:Android1.5

Type:Platform

APIlevel:3

Revision:4

Skins:HVGA(default),HVGA-L,HVGA-P,QVGA-L,QVGA-P

Intheabovecase,youcanuseeither1orandroid-3asthetargetID.Inthesampleproject,Ichoseandroid-4,whichcorrespondstoAndroid1.6.

Oncetheprojectiscreated,youcantestifyourprojectbuildissetupcorrectlybytypingantatthecommandline.Seetheabovesectionforfurtherinstructions.

SynchronizingwithEclipse

IfyouopentheAntbuildscript,build.xml,inEclipse,youwillseeanerroronthesecondlineofthefileatthisline:<projectname="MainActivity"default="help">.TheproblemwiththislineisthatitissayingthatthedefaultAnttargetis"help",buttheactualAnttargetsusedinthebuildfileareimportedfromanotherlocation,whichtheEclipseeditordoesnotrecognize.Theimportisdoneattheline<taskdefname="setup",whichimportsAntfilesfromtheAndroidSDK.

Unfortunately,whilethiserrorisactiveinyourproject,youcannotdebugyourprojectfromEclipse,eventhoughtheAntbuild.xmlisnotneeded.Therearetwosolutions.Youcanremovedefault="help"fromthefile,whichwillremovetheerrorinEclipse.Ifyoudothis,andtypeantatacommandpromptwithoutanytargets(asopposedto"antrelease"),youwon'tgetthedefaulthelp.Or,youcancopytheimportedAntfilesdirectlyintoyourcode,whichisexactlywhatyoumustdoifyouwouldliketocustomizeyourbuild.Ifyoufollowthistutorial,youwon'thavetoworryaboutthiserror.SeetheCustomizingthebuildsectionformoreinformation.

Automaticallysigningyourapplication

Beforeanapplicationcanbedeliveredtoadevice,thepackagemustbesigned.WhendebuggingusingEclipse,thepackageistechnicallysignedwithadebuggingkey.(Alternatively,youcanbuildadebugpackageusingantdebug)ForactualapplicationsdeliveredtotheAndroidMarketplace,youneedtosignthemwitharealkey.Itisusefultoputthisstepintothebuildprocess.Ontopoftheeaseofautomatingtheprocess,itallowsyoutobuildyourapplicationinonestep.(One-stepbuildsareaGoodIdeaTM)

Ifyouhavenotalreadycreatedakey,youcandosoautomaticallyusingEclipse(Rightclickproject>AndroidTools>ExportSignedApplicationPackage...),orfollowtheinstructionshere.

Nowwemusttellthebuildscriptaboutourkeystore.Createafilecalledbuild.propertiesinyourproject'sbasedirectory(inthesamedirectoryasbuild.xmlandtheotherpropertiesfiles),ifitdoesnotalreadyexist.Addthefollowinglines:

key.store=keystore

key.alias=www.androidengineer.com

Wherekeystoreisthenameofyourkeystorefileandchangethevalueofkey.aliastoyourkeystore'salias.Nowwhenyourunantrelease,youwillbepromptedforyourpasswords,andthebuildwillautomaticallysignandzipalignyourpackage.

Ofcourse,havingtoenteryourpassworddoesn'tmakeforaone-stepbuildprocess.Soyoucouldnotusethisforanautomatedbuildmachine,foronething.Italsohasthedisadvantageofrequiringyoutotypethepassword,whichitwilldisplayclearlyonthescreen,whichmaybeasecurityissueinsomecircumstances.Wecanputthepasswordsintobuild.propertiesaswell,whichwillsolvetheissue:

key.store.password=password

key.alias.password=password

Caution:Therecanbeseveralissueswithstoringthekeystoreandpasswords.Dependingonyourorganization'ssecuritypolicies,youmaynotbeabletostorethepasswordsinversioncontrol,oryoumaynotbeabletogiveouttheinformationtoalldeveloperswhohaveaccesstothesource.Ifyouwanttocheckinthekeystoreandthebuild.propertiesfile,butnotthepasswords,youcancreateaseparatepropertiesfilewhichcouldonlybeallowedoncertainmachinesbutnotcheckedintoversioncontrol.Forexample,youcouldcreateasecure.propertiesfilewhichgoesonthebuildmachine,butnotcheckedintoversioncontrolsoalldeveloperswouldn'thaveaccesstoit;importtheextrapropertiesfilebyadding<propertyfile="secure.properties"/>tobuild.xml.Finally,youcouldalwaysbuildtheAPKsunsignedwithantreleasebynotaddinganyinformationtothepropertiesfiles.Thepackagebuiltusingthismethodwillneedtobesignedandaligned.

Customizingthebuild

Nowthatwe'vegotaworkingAntbuildscript,wecancreateaone-stepbuild.Butifwewanttocustomizethebuildfurther,we'llhavetodoafewextrasteps.YoucandoanythingwithyourbuildthatyoucandowithAnt.Thereareafewthingswe'llhavetodofirst.

TheAnttargetsareactuallylocatedintheAndroidSDK.Thetargetsarewhatyoutypeafterantonthecommandline,suchasrelease,clean,etc.Tocustomizethebuildfurther,weneedtocopytheimportedtargetsintoourownbuildfile.

Ifyoulookinbuild.xml,youcanseetheinstructionsforhowtocustomizeyourbuildsteps:

Therulesfileisimportedfrom

<SDK>/platforms/<target_platform>/templates/android_rules.xml

Tocustomizesomebuildstepsforyourproject:

-copythecontentofthemainnode<project>fromandroid_rules.xml

-pasteitinthisbuild.xmlbelowthe<setup/>task.

-disabletheimportbychangingthesetuptaskbelowto<setupimport="false"/>

Findtheandroid_rules.xmlfileinyourAndroidSDK.Forexample,mineislocatedatC:\dev\android-sdk-windows\platforms\android-4\templates.There,copyalmosttheentirefile,excludingtheprojectnode(copybelow<projectname="MainActivity">toabove</project>),andpasteitinyourbuild.xmlfile.Also,changetheline<setup/>to<setupimport="false"/>.

Nowyoucanchangearoundthebuildasyouplease.Testthatthebuildfileisstillworkingproperlybyrunningabuild.Foranexampleofwhatyoucandowiththecustombuildscript,seethenextsection.

UsingaJavaconfigurationfile

ThisisagreatwaytouseabuildpropertytoaffectthesourcecodeofyourAndroidapplication.Imagineaconfigurationclassinyourprojectwhichsetssomevariables,suchasadebuggingflagoraURLstring.Youprobablyhaveadifferentsetofthesevalueswhendevelopingthanwhenyoureleaseyourapplication.Forexample,youmayturntheloggingflagoff,orchangetheURLfromadebuggingservertoaproductionserver.

publicclassConfig

{

/**Whetherornottoincludeloggingstatementsintheapplication.*/

publicfinalstaticbooleanLOGGING=true;

}

ItwouldbenicetohavetheaboveLOGGINGflagbesetfromyourbuild.Thatway,youcanbesurethatwhenyoucreateyourreleasepackage,allofthecodeyouusedfordebuggingwon'tbeincluded.Forexample,youmayhavedebugginglogstatementslikethis:

if(Config.LOGGING)

{

Log.d(TAG,"[onCreate]Success");

}

Youwillprobablywanttoleavethesestatementsonduringdevelopment,butremovethematrelease.Infact,itisgoodpracticetoleaveloggingstatementsinyoursourcecode.Ithelpswithlatermaintenancewhenyou,andespeciallyothers,needtoknowhowyourcodeworks.Ontheotherhand,itisbadpracticeforanapplicationtolittertheAndroidlogwithyourdebuggingstatements.Usingtheseconfigurationvariablesallowsyoutoturntheloggingonandoff,whilestillleavingthesourcecodeintact.

AnothergreatadvantageofusingthismethodofloggingisthatthebytecodecontainedwithintheloggingstatementcanbecompletelyremovedbyaJavabytecodeshrinkersuchasProGuard,whichcanbeintegratedintoyourbuildscript.I'lldiscusshowtodothisinalaterblogpost.

AnicewaytosettheConfig.LOGGINGflagisinyourbuildproperties.Addthefollowingtobuild.properties:

#Turnonorofflogging.

config.logging=true

Tohavethisbuildpropertybeincorporatedintooursourcecode,IwillusetheAnttypefiltersetwiththecopytask.WhatwecandoiscreateaJavatemplatefilewhichhastokenssuchas@CONFIG.LOGGING@andcopyittooursourcedirectory,replacingthetokenswithwhateverthebuildpropertiesvaluesare.Forexample,inthesampleapplicationIhaveafilecalledConfig.javaintheconfig/directory.

publicclassConfig

{

/**Whetherornottoincludeloggingstatementsintheapplication.*/

[email protected]@;

}

Pleasenotethatthisisnotasourcefile,andthatconfig/Config.javaisnottheactualfileusedwhencompilingtheproject.Thefilesrc/com/yourpackage/Config.java,whichisthecopiedfiledestination,iswhatwillbeusedasasourcefile.

NowIwillalterthebuildfiletocopythetemplatefiletothesourcepath,[email protected],whichistrue.IwillcreateanAnttargetcalledconfigwhichwillcopytheabovetemplatetothesourcedirectory.Thiswillbecalledbeforethecompiletarget.

<!--CopyConfig.javatooursourcetree,replacingcustomtokenswithvaluesinbuild.properties.Theconfigurationdependson"clean"becauseotherwisethebuildsystemwillnotdetectchangesintheconfiguration.-->

<targetname="config">

<propertyname="config-target-path"value="${source.dir}/com/androidengineer/antbuild"/>

<!--Copytheconfigurationfile,replacingtokensinthefile.-->

<copyfile="config/Config.java"todir="${config-target-path}"

overwrite="true"encoding="utf-8">

<filterset>

<filtertoken="CONFIG.LOGGING"value="${config.logging}"/>

</filterset>

</copy>

<!--Nowsetittoread-only,aswedon'twantpeopleaccidentally

editingthewrongone.NOTE:Thisstepisunnecessary,butIdo

itsothedevelopersrememberthatthisisnottheoriginalfile.-->

<chmodfile="${config-target-path}/Config.java"perm="-w"/>

<attribfile="${config-target-path}/Config.java"readonly="true"/>

</target>

TomakethisAnttargetexecutebeforethecompiletarget,wesimplyaddconfigtothedependencyofcompile:<targetname="compile"depends="config,-resource-src,-aidl".Wealsomaketheconfigtargetcallclean,becauseotherwisethebuildsystemwillnotdetectchangesintheconfiguration,andmaynotrecompiletheproperclasses.

Note:TheaboveAnttasksetsthetargetfile(inyoursourcedirectory)toread-only.Thisisnotnecessary,butIadditasaprecautiontoremindmethatitisnottheoriginalfilethatIneedtoedit.Whendeveloping,Iwillchangetheconfigurationsometimeswithoutusingthebuild,andEclipsewillautomaticallychangethefilefromread-onlyforme.Ialsodonotcheckinthetargetfileintoversioncontrol;onlytheoriginaltemplateandbuild.properties.

Versioncontrol

Donotcheckinthelocal.propertiesfilewhichisgeneratedbytheAndroidbuildtools.Thisisnotedinthefileitself;itsetspathsbasedonthelocalmachine.Docheckinthedefault.propertiesfile,whichisusedbytheAndroidtools,andbuild.properties,whichisthefilewhichyouedittocustomizeyourproject'sbuild.

Ialsodon'tcheckinthetargetConfig.javainthesourcedirectory,noranythingelseisconfiguredbythebuild.Idon'twantlocalchangestopropagatetootherdevelopers,soIonlycheckintheoriginaltemplatefileintheconfig/directory.

Inmyprojects,whenIreleaseanewversionofaprojectIalwayscheckinthepropertiesfileandtagitinthesourcerepositorywithatagnamesuchas"VERSION_2.0".Thatwaywearecertainofwhatpropertiestheapplicationwasbuiltwith,andwecanreproducetheapplicationexactlyasitwasreleased,ifwelaterneedto.

Summary

1.Atthecommandlinerunandroidcreateproject,orandroidupdateprojectinyourprojectbasedirectoryifitalreadyexists.

2.(Optional)Addkey.storeandkey.aliastobuild.propertiesifyouwanttoincludethesigningstepinyourbuild.

3.(Optional)Addkey.store.passwordandkey.alias.passwordtobuild.propertiesifyouwanttoincludethekeystorepasswords,tomakethebuildrunwithoutanyfurtherinputneeded.

4.(Optional)Ifyouwouldliketofurthercustomizethebuild,copytheSDKAntbuildcodefrom<SDK>/platforms/<target_platform>/templates/android_rules.xmltoyourlocalbuild.xmlandchange<setup/>to<setupimport="false"/>.

5.Useantreleasetobuildyourproject.Itwillcreatethepackageinbin/.

SampleApplication

ThesampleapplicationisasimpleHelloWorldapplication,butitalsoincludesthecustombuildscriptasdescribedinthistutorial.ItalsoincludestheConfig.javawhichisconfigurablebythebuild.First,youmustrun"androidupdateproject-p."fromthecommandlineintheproject'sdirectorytoletthetoolssettheSDKpathinlocal.properties.Thenyoucanturnonandoffloggingbychangingthevalueofconfig.logginginbuild.properties.Finally,runantreleasetobuildtheapplication,whichwillcreatethesignedbin/MainActivity-release.apkfilereadytobereleased.

Projectsourcecode-antbuild.zip(13.4Kb)

PostedbyMattQuigleyat2:41AM

EmailThisBlogThis!SharetoTwitterSharetoFacebook

Labels:ant,build

55comments:

Adecussaid...

WhenIrunantreleaseIgetallkindsoferrorsbecauseitcan'tfindanyofthedependencies.IsthereaneasywaytoincludetheprojectdependenciesordoIhavetomanuallyincludethembymodifyingbuild.xml?(Ihavedependenciestojarfilesandotherjavaprojects)

Ithoughtthewholepointofusingtheeclipseprojecttobuildisbecauseitknowsaboutdependenciesandthefullprojectstructure,otherwiseImindaswelljustmanuallymakejavaccallswithallthedependenciesincluded.

August23,2010at10:05AM

MattQuigleysaid...

@Adecus

IfyourprojectbuildscorrectlyinEclipse,andafterthatyoucreatethebuildfileusingthe"androidupdate"commandbutthebuildfiledoesn'twork,thenIsupposetheAndroidtoolswhichcreatetheprojectdonotsupportautomaticallyaddingdependenciestothebuildfile.Youprobablyhavetomanuallyupdateit.

August23,2010at11:57AM

Adecussaid...

Iwilltrythat.

Also,wellwritteninformativepost,thankyou.

August23,2010at12:16PM

ArmenB.said...

Iwashavingissuesreferencingalibarayproject.Ifoundthisinfohelpful:

http://www.listware.net/201006/android-developers/56532-android-developers-android-library-broken.html

August30,2010at6:51PM

vgpssaid...

Thanksalotforthisusefularticle.

August31,2010at10:34AM

ArmenB.said...

Doesanyoneknowhowtouseanttobuildanappthatislinksourcedtoalibraryproject?Thanks.

September2,2010at2:15PM

Anonymoussaid...

Veryusefultutorial.HadtoproperlysettheJAVA_HOME(withoutblanks)andPATH,butoncefiguredout,itworkedoutwellonWin7.Thanks!

September20,2010at6:21PM

TextToolsaid...

Greatarticleandgreatblog!Thanksforyourlessons,Ifindthemreallyuseful.

September24,2010at1:10PM

Anonymoussaid...

AfterlettingEclipseupdatetheadd-on,Iendedhavingissuesbuildingwithant(despitehavingnoproblemrightbeforeit).BasedonsomepostsIfound(fromGooglestaff),changesthatare*not*backward-compatible(thankyou!)wereintroducedinthebuildprocess.Thesolutionformyprojectwasnottouseandroid_rules.xmltomodifybuild.xml,butratherant_rules_r3.xml(under/tools/ant).Icouldapplytheothertasks(e.g.config)anditworkedfine.

September24,2010at5:59PM

alexsaid...

howdoIspecifythelibrary.jarfilesthatarelocatedintheproject's\libfolder?

IsthereanythingIneedtodoforthe.sofilesintheproject's\libs\armeabifolder?

CurrentlyIgetalotoferrorslike:"packageorg.anddev.andengine.enginedoesnotexist"

Eclipsebuiltitfine,butAntdoesn'tknowaboutthe\libitseemslike.

October10,2010at4:43AM

Alexsaid...

thesolutionwastocopytheandEnginelibraryJAR'stothe\libsfolder(Ihadthemin\lib)

October10,2010at5:26AM

Owensaid...

HiMatt,

excellentarticle.IhaveonlyeverusedEclipsefordevelopingandreleasingprojectsforandroid,untiltheuseofLVLandProgardbecameamusthave,forsecurity.

IamusingFlurryAnalyticsinmycode,sowhenIprocessandroidupdateandcreateabuild.xmlandlocal.propertiesfilewithrequiredchanges,Iproceedwithantrelease.Problemis,Iamgetting"packagecom.flurry.androidnotfound"errormessages.CanyoupossiblyexplainwhyImightbehavingthisproblemandwhatImaybedoingwrong?ShouldIincludetheFlurry.jarlocationinmybuildorpropertiesfiles?.Yourhelpwouldbegreatlyappreciated.

October11,2010at11:01AM

MattQuigleysaid...

@Owen

Ican'ttellifyou'regettingthoseerrorsatruntimeorduringthebuild.Inanycase,thedefaultfolderwhereadditionallibrariesgois./libs/.Youmightwanttotrycopyingthelibraryfile(whichIguessisa.jarfile)intothatfolder.Oryoucouldtrychangingbuildpropertiestochangethedefaultlibrarydirectory,butI'dsuggestgettingitworkingbymovingthe.jarfilefirst.

October11,2010at9:54PM

Owensaid...

HiMatt,

Sorry,Ishouldhaveexplainedtheproblemwasinthebuild.But.....

Thanksamillionyouareastar.Everythingworkedfine.Ialsoshouldhavenotedthepostprevioustomine(Alex)wherehehadandresolvedthesameproblem.

Googleneedscompetentsupportpeoplelikeyou...Keepupthegoodwork.Ithinkitisappreciatedbyall.

October13,2010at7:03AM

Owensaid...

HiMatt,

IamhavingalotofproblemstryingtoincludetheLicensingserviceinmyAntbuid.

Iamgettingthemessage:

"com.android.vending.licensingdoesnotexist."

"importcom.android.vending.licensing.AESObfuscator;"

default.propertiesfileentryinMyMainProject

android.library.reference.1=c:\\Users\\LeOwen\\LiveProject\\library

-----------------------------------

default.propertiesfileentryincom.android.vending.licensing

android.library=true

target=android-8

--------------------------------

AltoughIhavereadthegoogledocumentationIamstillhavingnoluck.

CanyoupossiblytellmewhatotherrequirementsIneedtotakeintoconsiderationforthistowork?

October15,2010at1:10PM

MattQuigleysaid...

@Owen

Isthisabuildoraruntimeerror,"com.android.vending.licensingdoesnotexist."?

Also,haveyoutriedjustcopyingtheappropriatelibraryfilesintothedefaultlibsfolder?Ifyoucangetthattowork,thentheproblemishowyou'reconfiguringthenewlibraryfolder.Ifyoucan't,thenitsoundsliketheremaybeadditionalproblemsthatIcouldhelpwith.

Iusealibraryinmyprojectatwork,anditworksfine,atleastwiththeAPIlevel7andbelowbuildsetups.Butthismaybesomethingspecialwiththecrazinessthatthelicensinglibraryhastodo,andifso,Iwilllookintoitfurtherifyougivemealittlemoreinsightintohowyou'vesetuptheproject.I'lltryincorporatingthelicensinglibraryintothesampleprojectmyself.BesuretotellmeeverythingIneedtotrytodoso,suchaswheretodownloadit.

October16,2010at12:16PM

Owensaid...

HiMatt,

IhaveresolvedtheproblemwiththeLVLlibraryandProguardusingtheANTbuildmethod.becauseOfuscatingisincluded,IhavedecidedtoputthefulldescriptioninyourOptimizing,ObfuscatingandShrinkingPost.

October29,2010at6:40AM

Owensaid...

ThefollowingprocesswasusedtoBuild,Optimize,ObfuscateandShrinkanandroidapp

ifusingwindowsandeclipse.ICreatedaseparateprojectfromeclipsetoavoidcorruptionthatmaybecausedbytyposorincorrect

projectconfigurationset-up.

1.

Createaprojectrootdirectoryandcopythefilesfromeclipseasfollows:

AndroidMainfest.xml

CLASSPATHfile

PROJECTfile

default.properties

Addyourmy.keystoretotherootdirectory

2.

Copytheeclipsedirectoriesintotheprojectrootdirectoryasfollows:

assets

bin

gen

res

src

3.

Createalibsdirectoryandcopyanylibrary*.jarfilestothedirectory.

Ifyouareusingflurry,thismaybeoneofthem.

4.

Createaproguarddirectory.

copytheproguard.jarfiletothedirectory.

createandedittheproguardconfig.txtfileaccordingtodocumentaionandyourprojectrequirements.

Iflibsisnotincludedintheproguardprocessatthebottomofbuild.xmlfile,thenitshouldbeincluded

intheconfig.txtfileasfollows:

-libraryjarspath/to/your/libs

TheLVL-keepstatementmustalsobeincluded:

-keepclasscom.android.vending.licensing.ILicensingService

Putconfig.txtintheproguarddirectory.

5.

locatethemarket_licensing\libarydirectorylocatedinyoureclipseprojectandcopyto

yourProjectpath.

ThefinalProjectPathsetupshouldconsistof:

PROJECTROOT

assets

bin

gen

res

src

libs(*.jars)

library(AndroidLVL)

proguard

6.

Ensureapathtotheandroid.sdk-windows/toolsdirectoryhasbeensetuporcdtothelocation.

enterandroidupdateproject--pathC:\path\to\your\project

Alocal.propertiesandbuild.xmlfilewillbecreatedintheprojectrooddirectory.

7.build.xml

Youmayneedtoeditandtailorthebuild.xmlfileforyourprojectrequirements.Icopied

theant_rules_r3.xmlfilelocatedinandroid-sdk-windows\tools\antintothebuildfile,andset

setupimport="false"

8.build.propertiesfile

Anyconfigurationchangesareplacedinthisfile.

IncludetheandroidLVLlibrarypathasfollows:

android.library.reference.1=library

Toautomateyoursigningprocess,addthekeystoreandpasswordstatements(dependingonyoursiterestrictions)

key.store=your.keystore

key.alias=youralias

key.store.password=yourkeystorepassword

key.alias.password=youraliaspassword

Iftheaboveinstructionsarefollowedortheprojectconfigurationhasbeensetupaccordingtoyour

ownrequirements,thennavigatetoyourProjectrootdirectoryandenter.

antrelease

Thebuildshouldcompletesuccessfully.

Iputmostoftheaboveinabatchscripttoautomatetheprocess.Youalsodon'tneedtocreate

aseparateprojectifyoufeelconfidentwithwhatisinplacefromeclipse,butyouwillhave

toincludeproguardandlibsinyoureclipsprojectpathandyouwon'thavecontrolofbuid.xmlorbuildproperties

forexternalsources.Itisuptoyou.

Goodluck.

October29,2010at11:39AM

Owensaid...

ThefollowingprocesswasusedtoBuild,Optimize,ObfuscateandShrinkanandroidapp

ifusingwindowsandeclipse.ICreatedaseparateprojectfromeclipsetoavoidcorruptionthatmaybecausedbytyposorincorrect

projectconfigurationset-up.

1.

Createaprojectrootdirectoryandcopythefilesfromeclipseasfollows:

AndroidMainfest.xml

CLASSPATHfile

PROJECTfile

default.properties

Addyourmy.keystoretotherootdirectory

2.

Copytheeclipsedirectoriesintotheprojectrootdirectoryasfollows:

assets

bin

gen

res

src

3.

Createalibsdirectoryandcopyanylibrary*.jarfilestothedirectory.

Ifyouareusingflurry,thismaybeoneofthem.

4.

Createaproguarddirectory.

copytheproguard.jarfiletothedirectory.

createandedittheproguardconfig.txtfileaccordingtodocumentaionandyourprojectrequirements.

Iflibsisnotincludedintheproguardprocessatthebottomofbuild.xmlfile,thenitshouldbeincluded

intheconfig.txtfileasfollows:

-libraryjarspath/to/your/libs

TheLVL-keepstatementmustalsobeincluded:

-keepclasscom.android.vending.licensing.ILicensingService

Putconfig.txtintheproguarddirectory.

5.

locatethemarket_licensing\libarydirectorylocatedinyoureclipseprojectandcopyto

yourProjectpath.

ThefinalProjectPathsetupshouldconsistof:

PROJECTROOT

assets

bin

gen

res

src

libs(*.jars)

library(AndroidLVL)

proguard

6.

Ensureapathtotheandroid.sdk-windows/toolsdirectoryhasbeensetuporcdtothelocation.

enterandroidupdateproject--pathC:\path\to\your\project

Alocal.propertiesandbuild.xmlfilewillbecreatedintheprojectrooddirectory.

7.build.xml

Youmayneedtoeditandtailorthebuild.xmlfileforyourprojectrequirements.Icopied

theant_rules_r3.xmlfilelocatedinandroid-sdk-windows\tools\antintothebuildfile,andset

setupimport="false"

8.build.propertiesfile

Anyconfigurationchangesareplacedinthisfile.

IncludetheandroidLVLlibrarypathasfollows:

android.library.reference.1=library

Toautomateyoursigningprocess,addthekeystoreandpasswordstatements(dependingonyoursiterestrictions)

key.store=your.keystore

key.alias=youralias

key.store.password=yourkeystorepassword

key.alias.password=youraliaspassword

Iftheaboveinstructionsarefollowedortheprojectconfigurationhasbeensetupaccordingtoyour

ownrequirements,thennavigatetoyourProjectrootdirectoryandenter.

antrelease

Thebuildshouldcompletesuccessfully.

Iputmostoftheaboveinabatchscripttoautomatetheprocess.Youalsodon'tneedtocreate

aseparateprojectifyoufeelconfidentwithwhatisinplacefromeclipse,butyouwillhave

toincludeproguardandlibsinyoureclipsprojectpathandyouwon'thavecontrolofbuid.xmlorbuildproperties

forexternalsources.Itisuptoyou.

Goodluck.

October29,2010at11:41AM

Premiersaid...

Canyougivemeanexampleforantbuild.xmlwithandroidlibraryproject?

Thanks

December3,2010at12:32PM

cisnkysaid...

Averyusefularticle.Thanks!!!

February20,2011at11:11AM

JayKhimanisaid...

Veryniceandusefulpost.Thanks

March6,2011at3:02PM

CanElmassaid...

Veryusefulandinformative.Thankyou.

March9,2011at7:24AM

Anonymoussaid...

Veryhelpfull!Thanks!

March15,2011at8:52AM

Alexsaid...

Makesuretousethefollowingrulesfileinsteadoftheoneintheplatform\templatefolder,otherwiseyouwillgetbuilderrorslikeaaptexecdoesn'tsupportthe"basename"attribute:

android-sdk\tools\ant\main_rules.xml

April22,2011at11:13AM

KumarBibeksaid...

Thanksalot.

April29,2011at12:10AM

KameshKompellasaid...

Thearticleiswellwritten.However,thefollowingmustbekeptinmindtoavoidthebaselineandothererrorspeoplehavereported.Ispentanhourgettingthistoworkandfinallydiscoveredtheproblemasdetailedhere:

http://stackoverflow.com/questions/4464461/compile-error-while-trying-to-compile-android-app-with-ant

May4,2011at2:31AM

L`OcuSsaid...

Youmademyday.

Manythanks.

May17,2011at1:42PM

AjayLDsaid...

Thanksalot!

June15,2011at3:11AM

lambtsaid...

Averyusefularticle.Thanks!

July14,2011at5:52AM

softllcsaid...

Thanksforthegreatpost.

Here'satipforusingtheandroidloggerwhenthephoneisnotconnected.

http://www.softllc.com/archives/125

August8,2011at11:56AM

Anonymoussaid...

Awesome!Veryinformative.

September14,2011at1:10AM

PiyushPatelsaid...

Kudostou,Excellentstuff!!

Iwasabletosetupmybuildsysteminlessthanhour.

Thanksamillion;D

September23,2011at8:49AM

KangTaroGakNgertiseosaid...

idontknowwhy,somanypeopletalkingaboutandroid,andidontknowtoo,whystevejobsisveryangryaboutthis?canyoumentiontome?

October29,2011at2:35PM

Basavrajsaid...

VeryhelpfulforallAndroiddevelopers

November17,2011at8:00AM

apilyuginasaid...

Thanksalotforyourarticle!http://www.enterra-inc.com/techzone/hopethiscoulsdbeuseful,too.

January12,2012at10:12PM

MichaelTotschnigsaid...

Thankyouforthisinterestingarticle.ThereisonethingIamwonderingabout:Youshowhowtosettheloggingflagfromthebuild,butinordertobetrulyuseful,IMHOyouwouldneedtohavethebuildsettheloggingflagdependentonifyoubuildfordebugorrelease,forexamplebydefiningthefilterwith

Whatdoyothink?

January29,2012at1:50AM

Anonymoussaid...

Thanksfordoingthisarticle.I'mnotsurewhyIfoundtheofficialdocssointimidating--thisisclearandeasy!

IdidfindonechangeintheAndroidversionI'mrunning.

Insteadofputtingthepropertiesinbuild.properties,theyneedtobeinant.properties

(Thedocssaytodothatnow,at"Buildsignedandaligned"on

http://developer.android.com/guide/developing/building/building-cmdline.html#ReleaseMode)

Thanksagain!Thisisagreattimesaver!!

January29,2012at11:05PM

Miguelsaid...

Thanksforthepost,veryinsightful!

February14,2012at4:07AM

Anonymoussaid...

Thanksforthisusefulpost!!

March25,2012at5:25PM

JuhaniLehtimäkisaid...

Greattutorial.ThiswasveryhelpfulThankyouforpostingit!

May18,2012at8:02AM

YuvalDagansaid...

Thatwasagreathelpforme

Thanksalot!!

June26,2012at2:53AM

Anonymoussaid...

Amusinghudson,anttobuildandroidapk,fornormalandroidprojectthebuildworksfine,buticreatednewandroidunifiedui,wherethebuildfailsatsetup,sayingupdateandroidproject,

butididit,stilltheerroristhere,anyhelp?

July12,2012at12:52PM

Anonymoussaid...

Amusinghudson,anttobuildandroidapk,fornormalandroidprojectthebuildworksfine,buticreatednewandroidunifiedui,wherethebuildfailsatsetup,sayingupdateandroidproject,

butididit,stilltheerroristhere,anyhelp?

July12,2012at12:54PM

Anonymoussaid...

Amusinghudson,anttobuildandroidapk,fornormalandroidprojectthebuildworksfine,buticreatednewandroidunifiedui,wherethebuildfailsatsetup,sayingupdateandroidproject,

butididit,stilltheerroristhere,anyhelp?

July12,2012at12:55PM

GaryFredericksaid...

Greatinfo.Iamabouttomodifyant/Eclipseandthishelpsalot.

July28,2012at9:12AM

m0skitosaid...

NicetutorialbutanengineerusingWindows...really?XD

October30,2012at9:17AM

VinothP.ssaid...

coulduplselboratethesamewiththehelppfHudson,thatwouldbemorehelpful

October30,2012at9:49AM

Anonymoussaid...

Hello,Ihavebeentryingtoexecutethesampleprojectgivenhere.ButwhenIbuildthe'build.xml'fileIamgettingthiserror-"taskdefclasscom.android.ant.SetupTaskcannotbefound".Alltheenvironmentvariablesaresetaccordingly.Icantfigureouttheproblem.Couldyoupleasehelpmeout.

January24,2013at6:35AM

Anonymoussaid...

buddyyouhavetosetupthisparticularenvironmentaspath"android-home=[YOURPATHHERE]"

untilyouspecifythesystemdoesn'tknowwheretheantsetupis,hopethiswillresolvethisissue

January24,2013at11:15PM

Anonymoussaid...

alsocheckthislink

http://blog.klacansky.com/matter-code/ant-taskdef-class-com-android-ant-setuptask-cannot-be-found

January24,2013at11:18PM

Anonymoussaid...

Howdoyousetthe"config.logging"propertytobetrueorfalsedependingonwhattargetyou'rebuilding?(debugorrelease)

February17,2013at5:31PM

MattQuigleysaid...

>Howdoyousetthe"config.logging"propertytobetrueorfalsedependingonwhattargetyou'rebuilding?(debugorrelease)

Seethesampleproject-theantbuildscriptdoesitforyou,dependingonwhetheryouarerunningthedebugorreleasebuild.

February18,2013at3:35AM

Unknownsaid...

Thiscommenthasbeenremovedbytheauthor.

May3,2013at5:35PM

GuyNicholassaid...

Thanksforthearticle.Istillhaveaquestionthough.

Wehaveabuildmachineforautomatedbuilding/testingandthatrunsthroughanantbuildscriptwhichIhavesetuptodoavarietyofthings.

WealsohaveEclipsesetupwithC/C++configurationsofdebug/release(thisisaJava&NDKproject),butwhatIneedtodoisbeabletotietheC/C++configtotheJavasidesuchthatIcangettheJavaandCcodeonthesamepagesotospeak.Haveyoudonethis?

Regards,Guy

May3,2013at5:36PM

PostaComment

NewerPostOlderPostHome

Subscribeto:PostComments(Atom)

SearchThisBlog

Loading...

AndroidEngineer

Loading...

Categories

ant(1)

build(1)

Themes(1)

UI(2)

BlogArchive

►2011(1)

►June(1)

▼2010(4)

►August(1)

►July(1)

▼June(2)

UsingAnttoAutomateBuildingAndroidApplication...

UsingThemesinAndroidApplications

AboutMe

MATTQUIGLEY

Iamasoftwaredeveloperwhohasbeenworkinginthefieldofmobilesoftwarefor10yearsnow.CurrentlyI'minvolvedinmanyexcitingnewAndroidprojects.

VIEWMYCOMPLETEPROFILE

Copyright©2010AndroidEngineer

先备注在这里,后面有时间在翻译和整理下,同学都可以看看,附上链接地址:

http://www.androidengineer.com/2010/06/using-ant-to-automate-building-android.html

可以参考下面链接:

http://www.cnblogs.com/stay/archive/2013/05/27/3102027.html

相关推荐