爱问 爱问共享资料 爱问分类
首页 > > > [android.开发书籍].Practical.Android.Projects.pdf

[android.开发书籍].Practical.Android.Projects.pdf

[android.开发书籍].Practical.Androi…

上传者: appleflashstudio
638次下载 0人收藏 暂无简介 简介 2011-03-24 举报

简介:[android.开发书籍].Practical.Android.Projects.pdf

JordanGreylingPracticalAndroidProjectsCompanioneBookAvailablePracticalAndroidProjectsTrim:7.5x9.25spine=0.8125"424pagecount534ppiBuildingcoolscripts,apps,andgamesforAndroidSmartphonesLucasJordan|PieterGreylingCOMPANIONeBOOKSEELASTPAGEFORDETAILSON$10eBOOKVERSIONUS$39.99ShelveinMobileComputingUserlevel:Intermediate-Advancedwww.apress.comSOURCECODEONLINEBOOKSFORPROFESSIONALSBYPROFESSIONALSISBN978-1-4302-2629-1978143022629154499thisprintforcontentonly—size&colornotaccurateCYANMAGENTAYELLOWBLACKPANTONE123CSPOTMATTETakeapracticalapproachtobecomingaleading-edgeAndroiddeveloper,learningbyexamplewhilecombiningthemanytechnologiesneededtocre-ateasuccessful,up-to-datewebapp.PracticalAndroidProjectsintroducestheAndroidSDKanddevelopmenttoolsofthetrade,andthendivesintobuildingcool-lookingandfunappsthatputAn-droid’samazingcapabilitiestowork.Androidisthepowerful,full-featured,opensourcemobileplatformthatpowersphoneslikeGoogleNexus,MotorolaDroid,SamsungGalaxyS,andavarietyofHTCphonesandtabletcomputers.ThisbookhelpsyouquicklygetAndroidprojectsupandrunningwiththefreeandopensourceEclipse,NetBeans,andIntelliJIDEAIDEs.Thenyoubuildandex-tendmobileapplicationsusingtheAndroidSDK,Java,ScriptingLayerforAndroid,andlanguagessuchasPython,Ruby,Javascript/HTML,Flex/AIR,andLua.InPracticalAndroidProjectsyou’llworkonreal-worldprojectssuchas:•HostinganAndroidBASICinterpreter•ExtendingyourJava-basedAndroidapplicationswithembeddedLUA•ScriptingyourAndroiddevicewithSL4A•AddingTwitterandFacebooktoyourapplications•Using2Dgraphicsandanimationsforcasualgames•Creatingcross-platformappswithJavaScript/HTMLandFlexwithAIRPracticalAndroidProjectsisforanydevelopernewtotheAndroidplatformwhowantstolearntobuildmobileapplications.KnowledgeofthefundamentalsofJavaprogrammingisassumed.ISBN978-1-4302-3243-8978143023243853999ForyourconvenienceApresshasplacedsomeofthefrontmattermaterialaftertheindex.PleaseusetheBookmarksandContentsataGlancelinkstoaccessthem.DownloadfromWow!eBook<www.wowebook.com>ivContentsataGlanceContents..........................................................................................................vAbouttheAuthors...........................................................................................xAbouttheTechnicalReviewer........................................................................xiAcknowledgments.........................................................................................xiiPreface.........................................................................................................xiiiChapter1:AndroidFundamentals...................................................................1Chapter2:DevelopmentToolsinPractice....................................................49Chapter3:RollYourOwnAndroidScriptingEnvironment..........................105Chapter4:EmbeddingLuainAndroidApplications....................................155Chapter5:IntroducingSL4A:TheScriptingLayerforAndroid.................193Chapter6:CreatingaGUIwithHTML/JavaScriptandAIR..........................221Chapter7:UsingRESTwithFacebookandTwitter.....................................251Chapter8:UsingtheGoogleAppEnginewithAndroid................................275Chapter9:GameDevelopment:Graphics....................................................311Chapter10:GameDevelopment:Animation................................................341Chapter11:AppInventor............................................................................361Index............................................................................................................38711ChapterAndroidFundamentalsTheAndroidplatformisaveryexcitingyetrelativelynewplayerintoday’smobiledevicemarket.Beyondratingveryhighlyinthenumberofcoolfeaturesperdevice,Android-enabledsmartphonesarecurrentlyenjoyingthehighestpercentagesalesgrowthrateinthemobileindustry.AccordingtoGartnerResearch,1worldwidesalesofAndroid-basedsmartphonestoendusershavejumpedfromthenumber6spotin2009tonumber4bytheendofthefirstquarterof2010.Thislevelofgrowthisexpectedtocontinue.Infact,GartnerhaspredictedthatAndroidwillbecomethenumber2worldwidemobileoperatingsystemin2010andwillchallengeSymbianforthenumber1positionby2014.2Wewanttosharewithyousomeoftheenthusiasmwehaveforthistrulyremarkabledevelopmentplatform.Throughoutthecourseofthisbook,wewillattempttodothisbyshowingthewiderangeofopportunitiesavailableatyourfingertipswhenyouchoosetodevelopAndroidapplications.PerhapsyouarereadingthisbookinordertogainmorebackgroundunderstandingoftheAndroidplatform.Perhapsyouplantorollupyoursleevesandjoinusinrunningandplayingwiththeprojectsintheemulatororyourowndevice.WewanttogetyouupandrunningquicklyandprovideyouwithsufficientunderstandingoftheAndroidplatformandAndroidDevelopmentKit(ADK)developmentenvironmenttohavesuccesswithyourgoals.Withthosegoalsinmind,thischapteraimstobeaspracticalanintroductiontoAndroiddevelopmentaspossible.Italsostrivestocoverabroadspectrumofrequiredconceptualandtheoreticalbackgroundmaterialinaconciseandto-the-pointmanner.WewillstartwithashortdescriptionoftheAndroidplatformandthenjumpstraightintocoverageoftheinstallationoftheAndroidSDKandsupportingdevelopmenttools.TofullyroundoutourSDKsetupstudy,weembarkonastep-by-steptestdrivethat1FromGartnerpressrelease:http://www.gartner.com/it/page.jsp?id=13720132FromtheGartnerpressrelease:http://www.gartner.com/it/page.jsp?id=14346131CHAPTER1:AndroidFundamentals2involvesgeneratingabare-bonesAndroidprojectandgettingtheresultingskeletonAndroidapplicationupandrunningintheAndroidemulator.ThenextorderofbusinesswillbeatouroftheAndroidplatformarchitecture.HerewewilldescribetheAndroidplatformstack;Androidcomponentarchitecture;andDalvik,theAndroidruntime.Withthisknowledgeinhand,wethencoverworkingwiththeJavaIDEsEclipse,NetBeans,andIntelliJIDEACommunityEdition;plusspendsometimelearninghowtoequipthemwithAndroidprogrammingcapabilitiesviaplugins.Thismeanswehavealotofgroundtocover,solet'sgetstarted.WhatIsAndroid?Inanutshell,Androidisanoperatingsystemtargetedatmobilehardwaresuchasphonesandotherconstrainedcomputingdevicessuchasnetbooksandtabletcomputers.TheconceptandplatformwasthebrainchildofAndroidInc.,asmallstartupcompanyfromPaloAlto,California,thatwasacquiredbyGooglein2005.Itsstatedgoalwastocreateasmall,stable,flexible,andeasilyupgradedoperatingsystemforhandsetsthatwouldbehighlyattractivefordevicemanufacturersandtelephonycarriers.Androidplatformreleases1.xthrough2.xareaimedprimarilyatsmartphonedevices,whereasitisreportedthatAndroidrelease3.xwillbethefirstoperatingplatformspecificallydesignedwithhigh-endsupportfortabletcomputers.TheAndroidplatformwasoriginallyunveiledinNovember2007.TheunveilingcoincidedwiththeannouncementoftheformationoftheOpenHandsetAlliance,agroupofcompaniesthatsharethegoalofpromotingopenstandardsformobiledeviceplatformssuchasAndroid.InOctober2008,AndroidwasreleasedundertheApache2.0open-sourcelicense.3Thisandtheflexiblecomponent-baseddesignoftheplatformpresentinnovativeandcost-effectiveopportunitiesformanufacturersandsoftwaredevelopersalike.Weaimtoshowcasesomeofthesedistinguishingplatformcapabilitiesduringthecourseofthisbook.InstallingtheAndroidSDKWewillstartbyinstallingthecoreAndroidSDKandtools.OuraimistogettheAndroidemulatorwithourownsimpleapplicationupandrunningonanAndroidVirtualDevice(AVD)assoonaspossible.Theexperiencegainedwillthenserveasabasisforfurtherdiscussion.3http://source.android.com/source/licenses.htmlCHAPTER1:AndroidFundamentals3TheexamplesandcommandsyouwillbeshownwererunonamixtureofUbuntuGNU/Linux,MicrosoftWindows,andAppleMacOSXsystems.Allthetools,includingtheJDKandtheAndroidSDKtoolset,behaveinasimilar,ifnotidentical,manneracrossthemajorsupportedcomputingplatforms.JavaDevelopmentKit(JDK)Tobeginwith,youshouldhavearecentversionoftheJavaSDK(JDK)installedonyourparticularsystem.ItcanbeobtainedeitherfromyouroperatingsystemdistributionpackageinstallmanagerapplicationordirectlydownloadedfromtheInternet.4Weassumethatwedonotneedtogointothedetailsfordoingthis.SufficeittosaythatJDK5orupwardshouldbefine.ThiswritingisbasedonJDK6.CHECKINGTHEJDKVERSION:ToconfirmthatacompatibleversionoftheJDKisinstalledandavailabletotheenvironment,weusuallydoaquickcheckonthecommandlineorconsoleterminal,asfollows:$java–versionjavaversion"1.6.0_18"OpenJDKRuntimeEnvironment(IcedTea61.8.1)(6b18-1.8.1-0ubuntu1)OpenJDKServerVM(build16.0-b13,mixedmode)$javac–versionjavac1.6.0_18Ifsomethinggoeswrong,youshouldconsulttheJDKconfigurationdocumentationforyourparticularplatform.WewillnotcoverdebuggingJavainstallationshere.AndroidSDKandTargetPlatformsAssumingthatourJavaplatformisready,wenowneedtodownloadtheAndroidSDKstarterpackageanduseittoinstallourtargetAndroidplatforms.TheAndroidSDKstarterpackagecanbedownloadedfromtheofficialGoogleAndroidSDKdownloadsite.5Selectthedownloadappropriateforyourdevelopmentplatform.ThesupportedplatformscurrentlyincludeWindows,MacOSX(Intel),andLinux(i386).InthecaseofhavingdownloadedanSDKstarterpackagearchiveforLinuxorMacOSX,unpackthedownloadedarchiveintoadirectoryofyourchoice.4https://jdk6.dev.java.net/5http://developer.android.com/sdk/CHAPTER1:AndroidFundamentals4InthecaseofhavingdownloadedtheWindowsinstaller(.exefile),runtheinstallerandinstallintoadirectoryofyourchoice.Youcouldcallthisdirectoryanythingyoulike,butwerecommendsomethingsimilartothefollowing:LinuxorMacOSXsystem:~/android-sdk-linux_x86Windowssystem:C:\android-sdk-windowsMakeanoteofthisdirectorypathnameforlateruse.WithintherootoftheunpackeddirectorystructurethereshouldbeatextfilewithanamelikeSDKReadme.txt.Thishasspecificinstructionsforeachplatform.WhatisimportanttonotehereisthatthedownloadedarchivedoesnotincludethecompleteSDK.ThefollowingnotecontainsanextractfromthereadmeshippedwiththelatestAndroidSDKasofthiswriting.6READTHESDKREADME!TheAndroidSDKarchiveonlycontainsthetools.ItnolongercomespopulatedwithaspecificAndroidplatformorGoogleadd-on.Instead,youusetheSDKManagertoinstallorupdateSDKcomponentssuchasplatforms,tools,add-ons,anddocumentation.Inordertostartdevelopingapplications,youmustinstallatleastoneversionoftheAndroidplatformusingtheSDKManager.ThisrequiresanInternetconnection,soifyouplantousetheSDKoffline,pleasemakesuretodownloadthenecessarycomponentswhileonline.Atthispoint,itisrecommendedtoaddtheAndroidSDKtoolsdirectorytothedevelopmentenvironmentsystemPATHvariable.Thetoolsdirectorycanbefoundundertheprecedingunpackedrootdirectory:<sdk>/tools/.HavingthebinariesandtoolsonthepathwillmakeitalotmoreconvenienttoissueAndroidSDKcommandsfromanywhereontheterminalconsoleofyourdevelopmentsystem.Asanexample,afteraddingtheappropriateentriestotheshelluserloginscriptformyGNU/Linuxdevelopmentsystem,wereceivethefollowingoutputfromlistingitwiththeLinuxcatcommand:$cat~/.bashrc.....#--googleandroiddevtools--exportPATH="$PATH:~/android-sdk-linux_86/tools"exportPATH="$PATH:~/android-sdk-linux_86/platform-tools".....6AndroidSDKrelease8,Android2.3platformCHAPTER1:AndroidFundamentals5SETTINGTHEPATHONWINDOWS:Fromthedesktop,right-clickMyComputerandclickProperties.Alternatively,fromControlPanel,double-clickSystem.BothoptionsopentheSystemPropertiesdialogbox.NowclicktheAdvancedtab.IntheAdvancedsection,clicktheEnvironmentVariablesbutton.IntheEnvironmentVariableswindow,selectthePATHvariableintheUser-orSystemVariablesection,dependingonwhetheryouwantthesettingappliedforallusersorjustyourself.ClicktheEditbutton.Addormodifythepath.Directoriesareseparatedbyasemicolon.ClickOKwhendone.Forconfirmation,issuingthefollowingcommandonyourdevelopmentsystemwillprintthecurrentvalueofthesystemPATHvariabletotheterminalconsolewindow.LinuxandMacOSX:echo$PATHWindows:echo%PATH%AndroidPlatformAPILevelsTheAPIleveltargetedbyyourapplicationisveryimportantforreasonsofdevicecompatibilityandthesoftwaredevelopment-andmaintenancelifetimeofyourcodebase.Ifitisnotmanagedproperly,themaintenanceofyourapplicationcouldpotentiallybecomeanightmare,especiallyifitisdeployedtomultipleAndroiddevicesandoperatingplatforms.ItisalsoagoodideatobecomefamiliarwiththefolderstructuresoftheAndroidSDKonceitisinstalled.Again,thisisespeciallyvalidifyourapplicationswillbebuiltformultipleAndroidhardwaretargets.ForabetterunderstandingofthesubjectofAPIlevels,itiswellworththeeffortofreviewingthedocumentationfoundontheofficialdeveloper’swebsiteforAndroidAPIlevels.7Thetie-inbetweenAPIlevelnumbersandtheircorrespondingplatformsareclarifiedinTable1–1,whichwascurrentatthetimeofwriting.7http://developer.android.com/guide/appendix/api-levels.htmlCHAPTER1:AndroidFundamentals6Table1–1.AndroidPlatformVersionsandAPILevelsPlatformVersionAPILevelAndroid2.39Android2.28Android2.17Android2.0.16Android2.05Android1.64Android1.53Android1.12Android1.01AndroidPlatformSetupHereisashortlistofdependenciesforproceedingwiththesetupofSDKplatforms:AndroidSDKstarterpackagedownloadedandunpacked.TheJDK,ADK,andAnttoolsareaccessibleontheenvironmentpath.WehaveabasicunderstandingofAndroidplatformversionsandAPIlevels.Lastbutnotleast,weshouldbeconnectedtotheInternet.WecannowinstalltheSDKplatformcomponentsusingtheAndroidSDKandAVDManagerprograms.TostarttheSDKManageronLinuxorMacOSX,executethefollowingcommand:$androidTostarttheSDKManageronWindows,runthefollowingprogram:SDKManager.exeThemainuserinterfaceoftheAndroidSDKManageronLinuxshouldappearasinFigure1–1.CHAPTER1:AndroidFundamentals7Figure1–1.TheAndroidSDKandAVDManagerduringinitialSDKsetuponLinuxWINDOWSUSBDRIVERFORANDROIDDEVICES:ItisworthshowingtheequivalentAndroidSDKandAVDManagerfortheWindowsplatform(seeFigure1–2).Itcontainsanimportantaddition,theWindowsUSBDriverpackageforAndroiddevices.Thiswillbecomenecessarywhenyoudevelop,debug,anddeploydirectlyinconjunctionwithaphysicalAndroidphoneorotherAndroidhardwaredeviceattachedviaUSBcabletoaWindowscomputer.CHAPTER1:AndroidFundamentals8Figure1–2.TheAndroidSDKandAVDManagerduringinitialSDKsetuponWindowsNotethatinbothcaseswehaveselectedtheAndroid2.3platform,APIlevel9,plustherelevantadditionssuchasdocumentationandSDKsamples.NowclickInstallSelected.TheappropriateSDKresourcebundleswillnowbedownloadedandinstalledintotheSDKdirectorystructurewhereweunpackedtheSDKstarterarchive.InordertomaintainandupdateyourSDKovertime,anupdatesessioncanbedirectlyinitiatedfromthecommandlinebyexecutingthefollowingcommands:InaterminalsessiononLinux/MacOSX:$androidupdatesdkBesidestheoptionofsimplyrunningSDKManager.exeagain,thesamecanbeachievedfromtheWindowscommandpromptwiththefollowing:C:\>android.batupdatesdkCHAPTER1:AndroidFundamentals9Again,weassumethattheAndroidtoolscanbefoundonthesystempath.FurtherinformationaboutmanagingyourAndroidSDKinstallationcanbefoundontheAndroidDevelopers“AddingSDKComponents”page.8ExtraTools:ApacheAntTherearesomedevelopmenttoolsthatnoJavadevelopershoulddowithout.OnesuchanindispensableutilityisApacheAnt,whichisabuildtoolthatisJava'sroughequivalenttomake.makeistraditionallyusedinC/C++developmentenvironments.AntalsodiffersfrommakeinthatitusesXMLtospecifybuildstepsandactions.TheAndroidSDKextensivelyusesAntforitscompilation,build,anddeploymentinfrastructure.Wewilluseittotestdriveourcoretoolsinthenextsection.Soifitisnotalreadyinstalledonyoursystem,werecommendyougrabacopyandinstallit.Ifnecessary,youcanfindinstallationinstructionsandmoreinformationaboutAntontheofficialAntwebsite.9SOMEIDESALREADYCONTAINANT:IfyouwillbeusinganIDEexclusively,installingastand-aloneinstanceofApacheAntmightnotbenecessary.IDEssuchasEclipseandNetBeanscomepackagedwithanAntdistributionthattheyinvokebehindthescenesduringthebuildprocess.Ifyouareplanningtoworkthroughtheexamplesthatfollow,ensurethatAntisonthesystemenvironmentpathonceitisinstalled.AndroidSDKTestDriveWewillnowtakeourSDKandplatforminstallationforacomprehensivetestdrivetocompletetheinstallationofruntimecomponentsandtoconfirmthateverythingwassetupcorrectly.Wewillalsogettoknowtheenvironmentbetter.Thisisacentralpartofthischapterandwillformthebasisoffurthersubjectscovered.Initially,wewilldotheworkfromtheterminalconsole,commandline,orcommandprompt,whicheverterminologyisappropriateforyoursystemorpersonalpreference.1.CreateanapplicationprojectdirectorytoworkinandcallitHelloAndroidSdk.Fromwithinaparent-orhomedirectoryofyourchoicesomewhereonyoursystem,issuethefollowingcommands:OnLinuxorMacOSX:$mkdirHelloAndroidSdk$cdHelloAndroidSdk8http://developer.android.com/sdk/adding-components.html9http://ant.apache.org/DownloadfromWow!eBook<www.wowebook.

[android.开发书籍].Practical.Android.Projects.pdf

[android.开发书籍].Practical.Androi…

上传者: appleflashstudio
638次下载 0人收藏 暂无简介 简介 2011-03-24 举报

简介:[android.开发书籍].Practical.Android.Projects.pdf

JordanGreylingPracticalAndroidProjectsCompanioneBookAvailablePracticalAndroidProjectsTrim:7.5x9.25spine=0.8125"424pagecount534ppiBuildingcoolscripts,apps,andgamesforAndroidSmartphonesLucasJordan|PieterGreylingCOMPANIONeBOOKSEELASTPAGEFORDETAILSON$10eBOOKVERSIONUS$39.99ShelveinMobileComputingUserlevel:Intermediate-Advancedwww.apress.comSOURCECODEONLINEBOOKSFORPROFESSIONALSBYPROFESSIONALSISBN978-1-4302-2629-1978143022629154499thisprintforcontentonly—size&colornotaccurateCYANMAGENTAYELLOWBLACKPANTONE123CSPOTMATTETakeapracticalapproachtobecomingaleading-edgeAndroiddeveloper,learningbyexamplewhilecombiningthemanytechnologiesneededtocre-ateasuccessful,up-to-datewebapp.PracticalAndroidProjectsintroducestheAndroidSDKanddevelopmenttoolsofthetrade,andthendivesintobuildingcool-lookingandfunappsthatputAn-droid’samazingcapabilitiestowork.Androidisthepowerful,full-featured,opensourcemobileplatformthatpowersphoneslikeGoogleNexus,MotorolaDroid,SamsungGalaxyS,andavarietyofHTCphonesandtabletcomputers.ThisbookhelpsyouquicklygetAndroidprojectsupandrunningwiththefreeandopensourceEclipse,NetBeans,andIntelliJIDEAIDEs.Thenyoubuildandex-tendmobileapplicationsusingtheAndroidSDK,Java,ScriptingLayerforAndroid,andlanguagessuchasPython,Ruby,Javascript/HTML,Flex/AIR,andLua.InPracticalAndroidProjectsyou’llworkonreal-worldprojectssuchas:•HostinganAndroidBASICinterpreter•ExtendingyourJava-basedAndroidapplicationswithembeddedLUA•ScriptingyourAndroiddevicewithSL4A•AddingTwitterandFacebooktoyourapplications•Using2Dgraphicsandanimationsforcasualgames•Creatingcross-platformappswithJavaScript/HTMLandFlexwithAIRPracticalAndroidProjectsisforanydevelopernewtotheAndroidplatformwhowantstolearntobuildmobileapplications.KnowledgeofthefundamentalsofJavaprogrammingisassumed.ISBN978-1-4302-3243-8978143023243853999ForyourconvenienceApresshasplacedsomeofthefrontmattermaterialaftertheindex.PleaseusetheBookmarksandContentsataGlancelinkstoaccessthem.DownloadfromWow!eBook<www.wowebook.com>ivContentsataGlanceContents..........................................................................................................vAbouttheAuthors...........................................................................................xAbouttheTechnicalReviewer........................................................................xiAcknowledgments.........................................................................................xiiPreface.........................................................................................................xiiiChapter1:AndroidFundamentals...................................................................1Chapter2:DevelopmentToolsinPractice....................................................49Chapter3:RollYourOwnAndroidScriptingEnvironment..........................105Chapter4:EmbeddingLuainAndroidApplications....................................155Chapter5:IntroducingSL4A:TheScriptingLayerforAndroid.................193Chapter6:CreatingaGUIwithHTML/JavaScriptandAIR..........................221Chapter7:UsingRESTwithFacebookandTwitter.....................................251Chapter8:UsingtheGoogleAppEnginewithAndroid................................275Chapter9:GameDevelopment:Graphics....................................................311Chapter10:GameDevelopment:Animation................................................341Chapter11:AppInventor............................................................................361Index............................................................................................................38711ChapterAndroidFundamentalsTheAndroidplatformisaveryexcitingyetrelativelynewplayerintoday’smobiledevicemarket.Beyondratingveryhighlyinthenumberofcoolfeaturesperdevice,Android-enabledsmartphonesarecurrentlyenjoyingthehighestpercentagesalesgrowthrateinthemobileindustry.AccordingtoGartnerResearch,1worldwidesalesofAndroid-basedsmartphonestoendusershavejumpedfromthenumber6spotin2009tonumber4bytheendofthefirstquarterof2010.Thislevelofgrowthisexpectedtocontinue.Infact,GartnerhaspredictedthatAndroidwillbecomethenumber2worldwidemobileoperatingsystemin2010andwillchallengeSymbianforthenumber1positionby2014.2Wewanttosharewithyousomeoftheenthusiasmwehaveforthistrulyremarkabledevelopmentplatform.Throughoutthecourseofthisbook,wewillattempttodothisbyshowingthewiderangeofopportunitiesavailableatyourfingertipswhenyouchoosetodevelopAndroidapplications.PerhapsyouarereadingthisbookinordertogainmorebackgroundunderstandingoftheAndroidplatform.Perhapsyouplantorollupyoursleevesandjoinusinrunningandplayingwiththeprojectsintheemulatororyourowndevice.WewanttogetyouupandrunningquicklyandprovideyouwithsufficientunderstandingoftheAndroidplatformandAndroidDevelopmentKit(ADK)developmentenvironmenttohavesuccesswithyourgoals.Withthosegoalsinmind,thischapteraimstobeaspracticalanintroductiontoAndroiddevelopmentaspossible.Italsostrivestocoverabroadspectrumofrequiredconceptualandtheoreticalbackgroundmaterialinaconciseandto-the-pointmanner.WewillstartwithashortdescriptionoftheAndroidplatformandthenjumpstraightintocoverageoftheinstallationoftheAndroidSDKandsupportingdevelopmenttools.TofullyroundoutourSDKsetupstudy,weembarkonastep-by-steptestdrivethat1FromGartnerpressrelease:http://www.gartner.com/it/page.jsp?id=13720132FromtheGartnerpressrelease:http://www.gartner.com/it/page.jsp?id=14346131CHAPTER1:AndroidFundamentals2involvesgeneratingabare-bonesAndroidprojectandgettingtheresultingskeletonAndroidapplicationupandrunningintheAndroidemulator.ThenextorderofbusinesswillbeatouroftheAndroidplatformarchitecture.HerewewilldescribetheAndroidplatformstack;Androidcomponentarchitecture;andDalvik,theAndroidruntime.Withthisknowledgeinhand,wethencoverworkingwiththeJavaIDEsEclipse,NetBeans,andIntelliJIDEACommunityEdition;plusspendsometimelearninghowtoequipthemwithAndroidprogrammingcapabilitiesviaplugins.Thismeanswehavealotofgroundtocover,solet'sgetstarted.WhatIsAndroid?Inanutshell,Androidisanoperatingsystemtargetedatmobilehardwaresuchasphonesandotherconstrainedcomputingdevicessuchasnetbooksandtabletcomputers.TheconceptandplatformwasthebrainchildofAndroidInc.,asmallstartupcompanyfromPaloAlto,California,thatwasacquiredbyGooglein2005.Itsstatedgoalwastocreateasmall,stable,flexible,andeasilyupgradedoperatingsystemforhandsetsthatwouldbehighlyattractivefordevicemanufacturersandtelephonycarriers.Androidplatformreleases1.xthrough2.xareaimedprimarilyatsmartphonedevices,whereasitisreportedthatAndroidrelease3.xwillbethefirstoperatingplatformspecificallydesignedwithhigh-endsupportfortabletcomputers.TheAndroidplatformwasoriginallyunveiledinNovember2007.TheunveilingcoincidedwiththeannouncementoftheformationoftheOpenHandsetAlliance,agroupofcompaniesthatsharethegoalofpromotingopenstandardsformobiledeviceplatformssuchasAndroid.InOctober2008,AndroidwasreleasedundertheApache2.0open-sourcelicense.3Thisandtheflexiblecomponent-baseddesignoftheplatformpresentinnovativeandcost-effectiveopportunitiesformanufacturersandsoftwaredevelopersalike.Weaimtoshowcasesomeofthesedistinguishingplatformcapabilitiesduringthecourseofthisbook.InstallingtheAndroidSDKWewillstartbyinstallingthecoreAndroidSDKandtools.OuraimistogettheAndroidemulatorwithourownsimpleapplicationupandrunningonanAndroidVirtualDevice(AVD)assoonaspossible.Theexperiencegainedwillthenserveasabasisforfurtherdiscussion.3http://source.android.com/source/licenses.htmlCHAPTER1:AndroidFundamentals3TheexamplesandcommandsyouwillbeshownwererunonamixtureofUbuntuGNU/Linux,MicrosoftWindows,andAppleMacOSXsystems.Allthetools,includingtheJDKandtheAndroidSDKtoolset,behaveinasimilar,ifnotidentical,manneracrossthemajorsupportedcomputingplatforms.JavaDevelopmentKit(JDK)Tobeginwith,youshouldhavearecentversionoftheJavaSDK(JDK)installedonyourparticularsystem.ItcanbeobtainedeitherfromyouroperatingsystemdistributionpackageinstallmanagerapplicationordirectlydownloadedfromtheInternet.4Weassumethatwedonotneedtogointothedetailsfordoingthis.SufficeittosaythatJDK5orupwardshouldbefine.ThiswritingisbasedonJDK6.CHECKINGTHEJDKVERSION:ToconfirmthatacompatibleversionoftheJDKisinstalledandavailabletotheenvironment,weusuallydoaquickcheckonthecommandlineorconsoleterminal,asfollows:$java–versionjavaversion"1.6.0_18"OpenJDKRuntimeEnvironment(IcedTea61.8.1)(6b18-1.8.1-0ubuntu1)OpenJDKServerVM(build16.0-b13,mixedmode)$javac–versionjavac1.6.0_18Ifsomethinggoeswrong,youshouldconsulttheJDKconfigurationdocumentationforyourparticularplatform.WewillnotcoverdebuggingJavainstallationshere.AndroidSDKandTargetPlatformsAssumingthatourJavaplatformisready,wenowneedtodownloadtheAndroidSDKstarterpackageanduseittoinstallourtargetAndroidplatforms.TheAndroidSDKstarterpackagecanbedownloadedfromtheofficialGoogleAndroidSDKdownloadsite.5Selectthedownloadappropriateforyourdevelopmentplatform.ThesupportedplatformscurrentlyincludeWindows,MacOSX(Intel),andLinux(i386).InthecaseofhavingdownloadedanSDKstarterpackagearchiveforLinuxorMacOSX,unpackthedownloadedarchiveintoadirectoryofyourchoice.4https://jdk6.dev.java.net/5http://developer.android.com/sdk/CHAPTER1:AndroidFundamentals4InthecaseofhavingdownloadedtheWindowsinstaller(.exefile),runtheinstallerandinstallintoadirectoryofyourchoice.Youcouldcallthisdirectoryanythingyoulike,butwerecommendsomethingsimilartothefollowing:LinuxorMacOSXsystem:~/android-sdk-linux_x86Windowssystem:C:\android-sdk-windowsMakeanoteofthisdirectorypathnameforlateruse.WithintherootoftheunpackeddirectorystructurethereshouldbeatextfilewithanamelikeSDKReadme.txt.Thishasspecificinstructionsforeachplatform.WhatisimportanttonotehereisthatthedownloadedarchivedoesnotincludethecompleteSDK.ThefollowingnotecontainsanextractfromthereadmeshippedwiththelatestAndroidSDKasofthiswriting.6READTHESDKREADME!TheAndroidSDKarchiveonlycontainsthetools.ItnolongercomespopulatedwithaspecificAndroidplatformorGoogleadd-on.Instead,youusetheSDKManagertoinstallorupdateSDKcomponentssuchasplatforms,tools,add-ons,anddocumentation.Inordertostartdevelopingapplications,youmustinstallatleastoneversionoftheAndroidplatformusingtheSDKManager.ThisrequiresanInternetconnection,soifyouplantousetheSDKoffline,pleasemakesuretodownloadthenecessarycomponentswhileonline.Atthispoint,itisrecommendedtoaddtheAndroidSDKtoolsdirectorytothedevelopmentenvironmentsystemPATHvariable.Thetoolsdirectorycanbefoundundertheprecedingunpackedrootdirectory:<sdk>/tools/.HavingthebinariesandtoolsonthepathwillmakeitalotmoreconvenienttoissueAndroidSDKcommandsfromanywhereontheterminalconsoleofyourdevelopmentsystem.Asanexample,afteraddingtheappropriateentriestotheshelluserloginscriptformyGNU/Linuxdevelopmentsystem,wereceivethefollowingoutputfromlistingitwiththeLinuxcatcommand:$cat~/.bashrc.....#--googleandroiddevtools--exportPATH="$PATH:~/android-sdk-linux_86/tools"exportPATH="$PATH:~/android-sdk-linux_86/platform-tools".....6AndroidSDKrelease8,Android2.3platformCHAPTER1:AndroidFundamentals5SETTINGTHEPATHONWINDOWS:Fromthedesktop,right-clickMyComputerandclickProperties.Alternatively,fromControlPanel,double-clickSystem.BothoptionsopentheSystemPropertiesdialogbox.NowclicktheAdvancedtab.IntheAdvancedsection,clicktheEnvironmentVariablesbutton.IntheEnvironmentVariableswindow,selectthePATHvariableintheUser-orSystemVariablesection,dependingonwhetheryouwantthesettingappliedforallusersorjustyourself.ClicktheEditbutton.Addormodifythepath.Directoriesareseparatedbyasemicolon.ClickOKwhendone.Forconfirmation,issuingthefollowingcommandonyourdevelopmentsystemwillprintthecurrentvalueofthesystemPATHvariabletotheterminalconsolewindow.LinuxandMacOSX:echo$PATHWindows:echo%PATH%AndroidPlatformAPILevelsTheAPIleveltargetedbyyourapplicationisveryimportantforreasonsofdevicecompatibilityandthesoftwaredevelopment-andmaintenancelifetimeofyourcodebase.Ifitisnotmanagedproperly,themaintenanceofyourapplicationcouldpotentiallybecomeanightmare,especiallyifitisdeployedtomultipleAndroiddevicesandoperatingplatforms.ItisalsoagoodideatobecomefamiliarwiththefolderstructuresoftheAndroidSDKonceitisinstalled.Again,thisisespeciallyvalidifyourapplicationswillbebuiltformultipleAndroidhardwaretargets.ForabetterunderstandingofthesubjectofAPIlevels,itiswellworththeeffortofreviewingthedocumentationfoundontheofficialdeveloper’swebsiteforAndroidAPIlevels.7Thetie-inbetweenAPIlevelnumbersandtheircorrespondingplatformsareclarifiedinTable1–1,whichwascurrentatthetimeofwriting.7http://developer.android.com/guide/appendix/api-levels.htmlCHAPTER1:AndroidFundamentals6Table1–1.AndroidPlatformVersionsandAPILevelsPlatformVersionAPILevelAndroid2.39Android2.28Android2.17Android2.0.16Android2.05Android1.64Android1.53Android1.12Android1.01AndroidPlatformSetupHereisashortlistofdependenciesforproceedingwiththesetupofSDKplatforms:AndroidSDKstarterpackagedownloadedandunpacked.TheJDK,ADK,andAnttoolsareaccessibleontheenvironmentpath.WehaveabasicunderstandingofAndroidplatformversionsandAPIlevels.Lastbutnotleast,weshouldbeconnectedtotheInternet.WecannowinstalltheSDKplatformcomponentsusingtheAndroidSDKandAVDManagerprograms.TostarttheSDKManageronLinuxorMacOSX,executethefollowingcommand:$androidTostarttheSDKManageronWindows,runthefollowingprogram:SDKManager.exeThemainuserinterfaceoftheAndroidSDKManageronLinuxshouldappearasinFigure1–1.CHAPTER1:AndroidFundamentals7Figure1–1.TheAndroidSDKandAVDManagerduringinitialSDKsetuponLinuxWINDOWSUSBDRIVERFORANDROIDDEVICES:ItisworthshowingtheequivalentAndroidSDKandAVDManagerfortheWindowsplatform(seeFigure1–2).Itcontainsanimportantaddition,theWindowsUSBDriverpackageforAndroiddevices.Thiswillbecomenecessarywhenyoudevelop,debug,anddeploydirectlyinconjunctionwithaphysicalAndroidphoneorotherAndroidhardwaredeviceattachedviaUSBcabletoaWindowscomputer.CHAPTER1:AndroidFundamentals8Figure1–2.TheAndroidSDKandAVDManagerduringinitialSDKsetuponWindowsNotethatinbothcaseswehaveselectedtheAndroid2.3platform,APIlevel9,plustherelevantadditionssuchasdocumentationandSDKsamples.NowclickInstallSelected.TheappropriateSDKresourcebundleswillnowbedownloadedandinstalledintotheSDKdirectorystructurewhereweunpackedtheSDKstarterarchive.InordertomaintainandupdateyourSDKovertime,anupdatesessioncanbedirectlyinitiatedfromthecommandlinebyexecutingthefollowingcommands:InaterminalsessiononLinux/MacOSX:$androidupdatesdkBesidestheoptionofsimplyrunningSDKManager.exeagain,thesamecanbeachievedfromtheWindowscommandpromptwiththefollowing:C:\>android.batupdatesdkCHAPTER1:AndroidFundamentals9Again,weassumethattheAndroidtoolscanbefoundonthesystempath.FurtherinformationaboutmanagingyourAndroidSDKinstallationcanbefoundontheAndroidDevelopers“AddingSDKComponents”page.8ExtraTools:ApacheAntTherearesomedevelopmenttoolsthatnoJavadevelopershoulddowithout.OnesuchanindispensableutilityisApacheAnt,whichisabuildtoolthatisJava'sroughequivalenttomake.makeistraditionallyusedinC/C++developmentenvironments.AntalsodiffersfrommakeinthatitusesXMLtospecifybuildstepsandactions.TheAndroidSDKextensivelyusesAntforitscompilation,build,anddeploymentinfrastructure.Wewilluseittotestdriveourcoretoolsinthenextsection.Soifitisnotalreadyinstalledonyoursystem,werecommendyougrabacopyandinstallit.Ifnecessary,youcanfindinstallationinstructionsandmoreinformationaboutAntontheofficialAntwebsite.9SOMEIDESALREADYCONTAINANT:IfyouwillbeusinganIDEexclusively,installingastand-aloneinstanceofApacheAntmightnotbenecessary.IDEssuchasEclipseandNetBeanscomepackagedwithanAntdistributionthattheyinvokebehindthescenesduringthebuildprocess.Ifyouareplanningtoworkthroughtheexamplesthatfollow,ensurethatAntisonthesystemenvironmentpathonceitisinstalled.AndroidSDKTestDriveWewillnowtakeourSDKandplatforminstallationforacomprehensivetestdrivetocompletetheinstallationofruntimecomponentsandtoconfirmthateverythingwassetupcorrectly.Wewillalsogettoknowtheenvironmentbetter.Thisisacentralpartofthischapterandwillformthebasisoffurthersubjectscovered.Initially,wewilldotheworkfromtheterminalconsole,commandline,orcommandprompt,whicheverterminologyisappropriateforyoursystemorpersonalpreference.1.CreateanapplicationprojectdirectorytoworkinandcallitHelloAndroidSdk.Fromwithinaparent-orhomedirectoryofyourchoicesomewhereonyoursystem,issuethefollowingcommands:OnLinuxorMacOSX:$mkdirHelloAndroidSdk$cdHelloAndroidSdk8http://developer.android.com/sdk/adding-components.html9http://ant.apache.org/DownloadfromWow!eBook<www.wowebook.
  • 相关资料
  • 该用户的其他资料
  • 名称/格式
  • 下载次数
  • 资料大小
  • 名称/格式
  • 下载次数
  • 资料大小

用户评论

0/200
暂无评论
上传我的资料
关闭

请选择举报的类型

关闭

提示

提交成功!

感谢您对爱问共享资料的支持,我们将尽快核实并处理您的举报信息。

关闭

提示

提交失败!

您的举报信息提交失败,请重试!

关闭

提示

重复举报!

亲爱的用户!感觉您对爱问共享资料的支持,请勿重复举报噢!

全屏 缩小 放大
收藏
资料评价:

/ 418
所需积分:0 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!