【网学网提醒】:网学会员为您提供Android 官方 开发教程 andbook参考,解决您在Android 官方 开发教程 andbook学习中工作中的难题,参考学习。
y_er39(
网学)贡献
andbook!
release.002
AndroidProgramming
withTutorialsfromtheanddev.org-Community.
writtenbyNicolasGramlich
Checkforthelatestversionon
andbook.anddev.org
andbook-AndroidProgramming
Content
Foreword/Howtoreadthisdoc……5Introduction……6WhatisAndroid–aGPhone?……7
Androidfromabove……8
Openness……8Allapplicationsarecreatedequal……9Breakingdownapplicationboundaries……9Fast&;easyapplicationdevelopment……9
Thefirstweeks……12Dalvik.equals(Java)==false……13
DifferencestoanormalJavaVM……13
TheAndroidCodeChallenge……14CreatingAndroidApplications……15
AnatomyofanAndroidApplication……15
Activity……15IntentReceiver……17Service……17ContentProvider……18
AndroidUserInterfaces……19
HierarchyofScreenElements……19ComparingAndroidUIElementstoSwingUIElements……22
TheAndroidManifest.xml……23
General……24
……25……25
……25……25……25
2
poweredbyanddev.org
andbook-AndroidProgramming
……27……27……27
……28
ResourcesandthemagicR.java……29
Resources……29
Listofresources……29Usingresourcesincode……30ReferencingResources……31
AlternateResources&;Localization……32ThemagicR.java……33
HelloWorld–TheAndroidway.……34
InstallingtheAndroidSDK……35
TheAndroidDevelopmentTools(ADT)……35
Installationdone,let’sdosomecode……37
CreatinganewAndroidProject……37Runningyourfirstapplication……43
UIstheJavaway……45System.out.println(…)?……46
TheLogCat……46
UsingIntents……49
Starting(Sub)Activities……49
FindingXML-definedViewsinJava-Code……52HandlingClickstoViews……53ReturningvaluesfromSubActivities……56
PassingDatato(Sub)Activities……58
ImportantLayoutsandViewGroups……60
TheRelativeLayout……603
poweredbyanddev.org
andbook-AndroidProgramming
Bibliography……61Lostchapters……62
Thecommunities……62
4
poweredbyanddev.org
andbook-AndroidProgramming
Foreword/Howtoreadthisdoc
ThisdocumentwaswrittenfordeveloperswhohaveworkedwithJava?beforeandwanttostartdevelopingfortheAndroidPlatform.Itriedtomakethisasmuch“handson”aspossible,placingexamplecodeseverywhereitfit.AlsoItriedtoinsertasmanypictureaspossible,becausetheylivenupthelearningprocessandrelaxthereade
r’seyes.Butunfortunatelycodingisnoteverything;onehastolearnaboutsomebasicfactsoftheAndroidPlatformtofullyunderstand.Thatiswhatisdescribedonthefirst~XXXpages.Itisnotnecessarytoreadallthosedescribingpages,butitispreferable.Youcoulddecidetotreatitasakindofreference.Whatyouwouldreadthereisalsoexplainedwhenitoccursduringthe“handson”-process.SoyoucoulddirectlystartatHelloWorld–TheAndroidWay.Allcodesyouseeinthisdocument(thewholeworkspace)willbeavailableon:andbook.anddev.org/sources/
Havefunreading…
5
poweredbyanddev.org
andbook-AndroidProgramming
Introduction
TheOpenHandsetAlliance(1)releasedtheGoogleAndroidSDKonNovember12th,2007,havingannounceditaboutaweekbefore.Theimpactwasunbelievable,almosteveryIT/programming-relatednewspagedumpedanews-postabouttheSDKrelease–theGoogleGroups(2)wasoverwhelmedwithover2000MessageswithinthefirsttwoDays.TheideaoftheAndroidPlatformwasandstillisamazingandisofcourseattractingmoreandmoreprogrammerseveryday.EspeciallytheopenarchitecturebasedonIntentsandthepossibilitytoreplaceeventheHome-applicationgrantareallylargeamountofflexibilitytothewholeplatform.“Android–Imaginationisthelimit”1
1
NicolasGramlich–anddev.orgSite-Admin
6
poweredbyanddev.org
andbook-AndroidProgramming
WhatisAndroid–aGPhone?
TheweeksandmonthsbeforeGooglereleasedtheAndroidSDKtherehadbeenalotofrumorsaboutasocalledGPhone.ItwassaidtobeamobiledevicemanufacturedbyGoogleprovidingfreecommunicationbyshowingcontext-sensitiveadvertisementstotheuseronthedeviceitself.
Picture1RenderofapotentialGPhone
ButonNovember5th2007AndyRubin2announced:“[The]Android[Platform]–ismoresignificantandambitiousthanasinglephone.”GooglewithintheOpenHandsetAlliance(OHA)deliversacompletesetofsoftwareformobiledevices:anoperatingsystem,middlewareandkeymobileapplications.Whatwasreleasedaweeklaterwasnotafinalproduct,buta“FirstLookSDK”whatmanydidnotrealize.MajornewssitesgrabbedthediscomfortsofsomedeveloperswhosaidthatAndroidisfullofbugsandheavilylacksofdocumentation.ButthemajoritysaysthatAndroidisnotbuggierthananyothersoftwareatthisstage.
2
AndyRubin–GoogleDirectorofMobilePlatforms
7
poweredbyanddev.org
andbook-AndroidProgramming
Androidfromabove
Let’stakealookatwhattheOHAemphasizesonitsAndroidPlatform:Openness“Androidwasbuiltfromtheground-uptoenabledeveloperstocreatecompellingmobileapplicationsthattakefulladvantageofallahandsethastooffer.Itisbuilttobetrulyopen.Forexample,anapplicationcouldcalluponanyofthe
phone'scorefunctionalitysuchasmakingcalls,sendingtextmessages,orusingthecamera,allowingdeveloperstocreatericherandmorecohesiveexperiencesforusers.”Thisistrue,asadeveloperyoucandoeverything,fromsendingshortmessageswithjust2linesofcode,uptoreplacingeventheHOMEScreenofyourdevice.Onecouldeasilycreateafullycustomizedoperatingsystemwithinweeks,providingnomoreofGoogle’sdefaultapplicationtotheuser.“AndroidisbuiltontheopenLinuxKernel.Furthermore,itutilizesacustomvirtualmachinethathasbeendesignedtooptimizememoryandhardwareresourcesinamobileenvironment.Androidwillbeopensource;itcanbeliberallyextendedtoincorporatenewcuttingedgetechnologiesastheyemerge.Theplatformwillcontinuetoevolveasthedevelopercommunityworkstogethertobuildinnovativemobileapplications.”HereGoogleistalkingofthesocalledDalvikvirtualmachine(DalvikVM),whichisaregisterbasedvirtualmachine,designedandwrittenbyDanBornsteinandsomeotherGoogleengineers,tobeanimportantpartoftheAndroidplatform.Inthewords“registerbased”wefindthefirstdifferencetonormalJavavirtualmachines(JVM)whicharestackbased.Seethe“Dalvik.equals(Java)==false”-chapterformoredetailsonthatissue.
8
poweredbyanddev.org
andbook-AndroidProgramming
Allapplicationsarecreatedequal“Androiddoesnotdifferentiatebetweenthephone'scoreapplicationsandthird-partyapplications.Theycanallbebuilttohaveequalaccesstoaphone'scapabilitiesprovidinguserswithabroadspectrumofapplicationsandservices.WithdevicesbuiltontheAndroidPlatform,userswillbeabletofullytailorthephonetotheirinterests.Theycanswapoutthephone'shomescreen,thestyleofthedialer,oranyoftheapplications.Theycaneveninstructtheirphonestousetheirfavoritephotoviewingapplicationtohandletheviewingofallphotos.”Onceagainthisisalltrue.Developerscan100%customizetheirAndroidDevice.TheAndroidSystemCommunicationisbasedonsocalledIntents,whicharemoreorlessjustaString(withsomedataattached)whichdefinesanactionthatneedstobehandled.Anexampleforthisis:”android.provider.Telephony.SMS_RECEIVED”OnecansimplylistenonthatIntentbywritingabout5linesofdefinitions.ThesystemwouldthenrecognizethatthereismorethanoneapplicationthatwantstohandlethatIntentandasktheusertochoosewhichoneheorshewouldliketohandletheIntent.Breakingdownapplicationboundaries“Androidbreaksdownthebarrierstobuildingnewandinnovativeapplications.Forexample,adevelopercancombineinformationfromthewebwithdataonanindividual'smobilephone-suchastheuser'scontacts,calendar,orgeographiclocation-toprovideamorerelevantuserexperience.WithAndroid,adevelopercouldbuildanapplicationtha
tenablesuserstoviewthelocationoftheirfriendsandbealertedwhentheyareinthevicinitygivingthemachancetoconnect.”Fast&;easyapplicationdevelopment“Androidprovidesaccesstoawiderangeofusefullibrariesandtoolsthatcanbeusedtobuildrichapplications.Forexample,Android9
poweredbyanddev.org
andbook-AndroidProgramming
enablesdeveloperstoobtainthelocationofthedevice,andallowsdevicestocommunicatewithoneanotherenablingrichpeer-to-peersocialapplications.Inaddition,Androidincludesafullsetoftoolsthathavebeenbuiltfromthegroundupalongsidetheplatformprovidingdeveloperswithhighproductivityanddeepinsightintotheirapplications.”SincetheWeb2.0revolution,makingcontentrichapplicationswithinminutesisnomoreillusion.Androidhasbroughtdevelopingtounknownspeeds.Letmeprovideanexample:SomedayIstumbledovertheBuzzword‘DrivingDirections’withintheAndroid-Documentation.Thought–done.
Picture2GoogleDrivingDirectionsimplementationinAndroid
Thedevelopmentprocessoftheapplicationinthepictureabovetookabout1?hours!(Includingthesimpleuserinterfaceandallimagesyousee).Couldonecreatesuchasophisticatedapplicationonanyothermobile-platform?–No.
10
poweredbyanddev.org
andbook-AndroidProgramming
AdditionallythisapplicationcouldbeenrichedwiththecurrentGPSpositionofthedevicewithinahandfulofcode-lines.GoogleemphasizesAndroidspowerofprovidinglocation-based-services.GoogleMapsaresoneatwithinAndroidasifitwasjustdevelopedforAndroid.Onecanintegrateafullyzoomanddragenabledmapbyaddingjust3(!)charactersintheJava-CodeoftheAndroid-Default-Applicationand3linesofXML-Code.OthernicefeaturesthatareeasytousewithAndroidareAnimationsandmedia-playback.Sinceversionm5,theAndroidSDKcontainsfunctionsforstraightandreverseGeoCodingandinadditiontomp3,playbackof:ogg-Vorbis,MIDIandabunchofotherformats.
11
poweredbyanddev.org
andbook-AndroidProgramming
Thefirstweeks
Unfortunatelythedevelopershadtodealwithanotfullyimplementedpreview-SDK(initiallyreleasedbuild:‘m3-rc20’),whereevensomekeypartsoftheSDKwerepoorlydocumented.ThelackofdocumentationleadedtoanexplosionoftheAndroid-Developer-GroupwithintheGoogle-Groups.SoonerorlateronehadtorespectthestatementfromGoogle:“Ifitisnotdocumenteditisnotmeanttoworkyet.“ManydevelopersdidnotrealizethatfactthatthefirstSDKreleasedwerefirst-looksordeveloper-previews,wherechangesintheAPIhadtobeawaited.Anotherannoyingbugwasthechoppyemulator-sound,whichwassaidfixedwiththereleaseofbuild‘m3-rc37a’about4weekslater,butstillhappenedonsomesetupsuptom5.
12
poweredbyanddev.org
andbook-Android
Programming
Dalvik.equals(Java)==false
Why“Dalvik”?–TheDalvikvirtualmachinewasnamedbyBornsteinafterthefishingvillageofDalvíkinEyjafj?reur(Iceland),wheresomeofhisancestorslived.Asyoumayhaveheardof,DalvikisthenameofAndroid'svirtualmachine.Itisaninterpreter-onlyvirtualmachinethatexecutesfilesintheDalvikExecutable(*.dex)format,aformatthatisoptimizedforefficientstorageandmemory-mappableexecution.Thevirtualmachineisregister-based,anditcanrunclassescompiledbyaJavalanguagecompilerthathavebeentransformedintoitsnativeformatusingtheincluded"dx"tool.TheVMrunsontopofaLinux2.6kernel,whichitreliesonforunderlyingfunctionality(suchasthreadingandlowlevelmemorymanagement).TheDalvikVMwasalsooptimizedtoberunninginmultipleinstanceswithaverylowmemory-footprint.SeveralVMsprotectonesapplicationfrombeingdraggeddownbyanothercrashedApplication.DifferencestoanormalJavaVMJavaVM’sonecanfindonalmostanydesktopcomputernowadaysareStack-basedVirtualMachines(VM).TheDalvikVMontheotherhandisregisterbased,becauseonmobile-processorsareoptimizedforregisterbasedexecution.Alsoofregister-basedVMsallowfasterexecutiontimesattheexpenseofprogramswhicharelargeraftercompilation.
13
poweredbyanddev.org
andbook-AndroidProgramming
TheAndroidCodeChallenge
TheAndroidCodeChallenge(ADC)isanideaofGoogletoencouragethecommunitytobuildcoolapplicationsfortheAndroidPlatformbyrewardingthe50mostpromisingapplicationssubmitted.
Picture3AndroidDeveloperChallengeLogo
OfcoursetheAndroidDevelopersChallenge,withitsoverall10MillionDollarsofprizemoney,wasattractingevenmoresoftware-developerstocreateabunchofreallyusefulapplications.Ontheothersidemanyvoicessaid,thatthiswasnogoodchoicefromGoogle,becauseitwouldleadtolesscode-sharing,asmanywouldfearsharingtheirideaswithacommunity,duringthefirstimportantmonthsaftertheSDKrelease.ThereweretwoChallengesplanned:??AndroidDeveloperChallengeI:SubmissionsuptoApril14,2008AndroidDeveloperChallengeII:Thispartwilllaunchafterthefirsthandsetsbuiltontheplatformbecomeavailableinthesecondhalfof2008.
IntheAndroidDeveloperChallengeI,the50mostpromisingentriessubmittedbyApril14willeachreceivea$25,000awardtofundfurtherdevelopment.Thoseselectedwillthenbeeligibleforevengreaterrecognitionviaten$275,000awardsandten$100,000awards.ApplicationssubmittedtotheChallengeweresupposedtobeinnovativeanddemonstrateallthecapabilitiesoftheAndroidplatform,likelocationbasedservices,mediaconsumption,gamingandsocialnetworking,toenrichmobileexperience.14
poweredbyanddev.org
andbook-AndroidProgramming
CreatingAndroidA
pplications
InthischapterwewillconcentrateonthespecialtiesincreatinganyAndroid-Application.
AnatomyofanAndroidApplication
TherearefourbuildingblockstoanAndroidapplication:????ActivityIntentReceiverServiceContentProvider
Noteveryapplicationneedstohaveallfour,butyourapplicationwillbewrittenwithsomecombinationofthese.Onceyouhavedecidedwhatcomponentsyouneedforyourapplication,youshouldlisttheminafilecalledAndroidManifest.xml.ThisisanXMLfilewhereyoudeclarethecomponentsofyourapplicationandwhattheircapabilitiesandrequirementsare.Wewilldiscusssoon,whattheAndroidManifest.xmlisresponsiblefor.ActivityActivitiesarethemostcommonofthefourAndroidbuildingblocks.Anactivityisusuallyasinglescreeninyourapplication.EachactivityisimplementedasasingleclassthatextendstheActivitybaseclass.YourclasswilldisplayauserinterfacecomposedofViewsandrespondtoevents.Mostapplicationsconsistofmultiplescreens.Forexample,atextmessagingapplicationmighthaveonescreenthatshowsalistofcontactstosendmessagesto,asecondscreentowritethemessagetothechosencontact,andotherscreenstoreviewoldmessagesorchangesettings.Eachofthesescreenswouldbeimplementedasanactivity.Movingtoanotherscreenisaccomplishedbyastartinganewactivity.InsomecasesanActivitymayreturnavaluetothepreviousactivity-for15
poweredbyanddev.org
andbook-AndroidProgramming
exampleanactivitythatletstheuserpickaphotowouldreturnthechosenphototothecaller.Whenanewscreenopens,thepreviousscreenispausedandputontoahistorystack.Theusercannavigatebackwardthroughpreviouslyopenedscreensinthehistory.Screenscanalsochoosetoberemovedfromthehistorystackwhenitwouldbeinappropriateforthemtoremain.Androidretainshistorystacksforeachapplicationlaunchedfromthehomescreen.IntentandIntentFiltersAndroidusesaspecialclasscalledIntenttomovefromscreentoscreen.Intentdescribewhatanapplicationwantsdone.Thetwomostimportantpartsoftheintentdatastructurearetheactionandthedatatoactupon.TypicalvaluesforactionareMAIN(thefrontdooroftheapplication),VIEW,PICK,EDIT,etc.ThedataisexpressedasaUniformResourceIndicator(URI).Forexample,toviewawebsiteinthebrowser,youwouldcreateanIntentwiththeVIEWactionandthedatasettoaWebsite-URI.
newIntent(android.content.Intent.VIEW_ACTION,ContentURI.create("anddev.org"));
ThereisarelatedclasscalledanIntentFilter.Whileanintentiseffectivelyarequesttodosomething,anintentfilterisadescriptionofwhatintentsanactivity(orintentreceiver,seebelow)iscapableofhandling.AnactivitythatisabletodisplaycontactinformationforapersonwouldpublishanIntentFilterthatsaidtha
titknowshowtohandletheactionVIEWwhenappliedtodatarepresentingaperson.ActivitiespublishtheirIntentFiltersintheAndroidManifest.xmlfile.Navigatingfromscreentoscreenisaccomplishedbyresolvingintents.Tonavigateforward,anactivitycallsstartActivity(myIntent).Thesystemthenlooksattheintentfiltersforallinstalledapplicationsand16
poweredbyanddev.org
andbook-AndroidProgramming
pickstheactivitywhoseintentfiltersbestmatchesmyIntent.Thenewactivityisinformedoftheintent,whichcausesittobelaunched.TheprocessofresolvingintentshappensatruntimewhenstartActivityiscalled,whichofferstwokeybenefits:??ActivitiescanreusefunctionalityfromothercomponentssimplybymakingarequestintheformofanIntentActivitiescanbereplacedatanytimebyanewActivitywithanequivalentIntentFilter
IntentReceiverYoucanuseanIntentReceiverwhenyouwantcodeinyourapplicationtoexecuteinreactiontoanexternalevent,forexample,whenthephonerings,orwhenthedatanetworkisavailable,orwhenit'smidnight.IntentreceiversdonotdisplayaUI,althoughtheymaydisplayNotificationstoalerttheuserifsomethinginterestinghashappened.IntentreceiversarealsoregisteredinAndroidManifest.xml,butyoucanalsoregisterthemfromcodeusingContext.registerReceiver().Yourapplicationdoesnothavetoberunningforitsintentreceiverstobecalled;thesystemwillstartyourapplication,ifnecessary,whenanintentreceiveristriggered.ApplicationscanalsosendtheirownintentbroadcaststootherswithContext.broadcastIntent().ServiceAServiceiscodethatislong-livedandrunswithoutaUI.Agoodexampleofthisisamediaplayerplayingsongsfromaplaylist.Inamediaplayerapplication,therewouldprobablybeoneormoreactivitiesthatallowtheusertochoosesongsandstartplayingthem.However,themusicplaybackitselfshouldnotbehandledbyanactivitybecausetheuserwillexpectthemusictokeepplayingevenafternavigatingtoanewscreen.Inthiscase,themediaplayeractivitycouldstartaserviceusingContext.startService()toruninthebackgroundtokeepthemusicgoing.Thesystemwillthenkeepthemusicplaybackservice17
poweredbyanddev.org
andbook-AndroidProgramming
runninguntilithasfinished.(YoucanlearnmoreabouttheprioritygiventoservicesinthesystembyreadingLifeCycleofanAndroidApplication.)Notethatyoucanconnecttoaservice(andstartitifit'snotalreadyrunning)withtheContext.bindService()method.Whenconnectedtoaservice,youcancommunicatewithitthroughaninterfaceexposedbytheservice.Forthemusicservice,thismightallowyoutopause,rewind,etc.ContentProviderApplicationscanstoretheirdatainfiles,aSQLitedatabase,preferencesoranyothermechanismthatmakessense.Acontentprovider,however,isusefulifyo
uwantyourapplication'sdatatobesharedwithotherapplications.Acontentproviderisaclassthatimplementsastandardsetofmethodstoletotherapplicationsstoreandretrievethetypeofdatathatishandledbythatcontentprovider.
18
poweredbyanddev.org
andbook-AndroidProgramming
AndroidUserInterfaces
UserInterfaces(UI)inAndroidcanbebuiltwithintwoways,bydefiningXML-CodeorbywritingJava-Code.DefiningtheGUIstructureinXMLishighlypreferable,becauseasoneknowsfromtheModel-Viewer-ControlprinciplethattheUIshouldalwaysbeseparatedfromtheprogram-logic.Additionallyadaptingaprogramfromonescreen-resolutiontoanotherisaloteasier.DefiningaUIinXMLisverysimilartocreatingacommonHTMLdocument,whereyouhavei.e.suchasimplefile:
Thecontentofthebodyelement.
JustthesameasinAndroid’sXML-Layouts.Everythingiswellstructuredandcanbeexpressedbytree-structures:
HierarchyofScreenElementsThebasicfunctionalunitofanAndroidapplicationistheactivity-anobjectoftheclassandroid.app.Activity.Anactivitycandomanythings,butbyitselfitdoesnothaveapresenceonthescreen.TogiveyouractivityascreenpresenceanddesignitsUI,youworkwithviews
19
poweredbyanddev.org
andbook-AndroidProgramming
andviewgroups-basicunitsofuserinterfaceexpressionontheAndroidplatform.ViewsAviewisanobjectextendingthebaseclassandroid.view.View.It'sadatastructurewhosepropertiesstorethelayoutandcontentforaspecificrectangularareaofthescreen.AViewobjecthandlesmeasuring,itslayout,drawing,focuschanges,scrolling,andkey/gesturesforthescreenareaitrepresents.TheViewclassservesasabaseclassforallwidgets-asetoffullyimplementedsubclassesthatdrawinteractivescreenelements.Widgetshandletheirownmeasuringanddrawing,soyoucanusethemtobuildyourUImorequickly.Thelistofwidgetsavailableincludesi.e.TextView,EditText,Button,RadioButton,Checkbox,ScrollView,…ViewgroupsAviewgroupisanobjectofclassandroid.view.Viewgroup.Asitsnameindicates,aviewgroupisaspecialtypeofviewobjectwhosefunctionistocontainandmanageasubordinatesetofviewsandotherviewgroups,ViewgroupsletyouaddstructuretoyourUIandbuildupcomplexscreenelementsthatcanbeaddressedasasingleentity.TheViewgroupclassservesasabaseclassforlayouts-asetoffullyimplementedsubclassesthatprovidecommontypesofscreenlayout.Thelayoutsgiveyouawaytobuildastructureforasetofviews.ATree-StructuredUIOntheAndroidplatform,youdefineanActivity'sUIusingatreeofviewandviewgroupnodes,asshowninthediagrambelow.The
treecanbeassimpleorcomplexasyouneedtomakeit,andyoucanbuilditupusingAndroid'ssetofpredefinedwidgetsandlayoutsorcustomviewtypesthatyoucreateyourself.
20
poweredbyanddev.org
andbook-AndroidProgramming
Picture4AndroidUI-Treestructure
Toattachthetreetothescreenforrendering,yourActivitycallsitssetContentView()methodandpassesareferencetotherootnodeobject.OncetheAndroidsystemhasthereferencetotherootnodeobject,itcanworkdirectlywiththenodetoinvalidate,measure,anddrawthetree.WhenyourActivitybecomesactiveandreceivesfocus,thesystemnotifiesyouractivityandrequeststherootnodetomeasureanddrawthetree.Therootnodethenrequeststhatitschildnodesdrawthemselves-inturn,eachviewgroupnodeinthetreeisresponsiblefordrawingitsdirectchildren.Asmentionedpreviously,eachviewgrouphastheresponsibilityofmeasuringitsavailablespace,layingoutitschildren,andcallingdraw()oneachchildtoletitrenderitself.Thechildrenmayrequestasizeandlocationintheparent,buttheparentobjecthasthefinaldecisiononwherehowbigeachchildcanbe.
21
poweredbyanddev.org
andbook-AndroidProgramming
ComparingAndroidUIElementstoSwingUIElementsAssomedeveloperswhoarereadingthishaveprobablycodedUIswithSwingbeforeherearesomesimilaritiesbetweenAndroidandSwing.?????ActivitiesinAndroidrefersalmosttoa(J)FrameinSwing.ViewsinAndroidrefersto(J)ComponentsinSwing.TextViewsinAndroidreferstoa(J)LabelsinSwing.EditTextsinAndroidreferstoa(J)TextFieldsinSwing.ButtonsinAndroidreferstoa(J)ButtonsinSwing.
SettinglistenerstoaViewisnearlythesameinAndroidthaninSwing.
//AndroidmyView.setOnClickListener(newOnClickListener(){……//SwingmyButton.addActionListener(newActionListener(){……
22
poweredbyanddev.org
andbook-AndroidProgramming
TheAndroidManifest.xml
TheAndroidManifest.xmlisarequiredfileforeveryAndroidapplication.Itislocatedintherootfolderoftheapplication,anddescribesglobalvaluesforyourpackage,includingtheapplicationcomponents(activities,services,etc)thatthepackageexposestothe‘outerworld’,whatkindofdataeachofourActivitiesandco.canhandle,andhowtheycanbelaunched.AnimportantthingtomentionofthisfileareitssocalledIntentFilters.Thesefiltersdescribewhereandwhenthatactivitycanbestarted.Whenanactivity(ortheoperatingsystem)wantstoperformanactionsuchasopenaWebpageoropenacontactpickerscreen,itcreatesanIntentobject.ThisIntent-objectcanholdseveralinformationdescribingwhatyouwanttodo,whatdataisneededtoaccomplishitandotherbitsofinformation.AndroidcomparestheinformationinanIntentobjectwiththeintentfilterexposedbyeveryapp
licationandfindstheactivitymostappropriatetohandlethedataoractionspecifiedbythecaller.IfthereitmorethanoneapplicationcapableofhandlingthatIntent,theusergetsasked,whichapphewouldpreferhandlingit.Besidesdeclaringyourapplication'sActivities,ContentProviders,Services,andIntentReceivers,youcanalsospecifypermissionsinAndroidManifest.xml.
23
poweredbyanddev.org
andbook-AndroidProgramming
General
AverysimpleAndroidManifest.xmllookslikethis:
AlmosteveryAndroidManifest.xml(aswellasmanyotherAndroidXMLfiles)willincludethenamespacedeclaration
(xmlns:android=schemas.android/apk/res/android)
initsfirstelement.ThismakesavarietyofstandardAndroidattributesavailableinthefile,whichwillbeusedtosupplymostofthedataforelementsinthatfile.Almosteverymanifestincludesasingletag,whichitselfcontainsseveraltagsdescribingApplications,IntentReceivers,etc…thatareavailableinthisapplication.IfyouwanttomakeanActivitylaunchabledirectlythroughtheuser,youwillneedtomakeitsupporttheMAINactionandLAUNCHERcategory,whatresultasshownhere:
Picture5DirectlylaunchableActivity
24
poweredbyanddev.org
andbook-AndroidProgramming
WhatfollowsisadetailedlistofthestructureofanAndroidManifestfile,describingallavailable
,withanExampleforeach:ThisistherootnodeofeachAndroisManifest.xml.Itcontainsthepackage-attribute,whichpointstoanypackageinoutActivity.OtherActivities-pathwillbaserelativetoitsvalue.
Describesasecuritypermission,whichyourpackagemustbegrantedinorderforittooperatecorrectly(i.e.whenyouwanttosendSMSorusethePhone-Contacts).Thepermissionsgetgrantedbytheuserduringinstallationofyourapplication.Quantity:0+
Declaresasecuritypermissionthatcanbeusedtorestrictwhichapplicationscanaccesscomponentsorfeaturesinyour(oranother)package.Quantity:0+Declaresthecodeofaninstrumentationcomponentthatisavailabletotestthefunctionalityofthisoranotherpackage.SeeInstrumentationformoredetails.Quantity:0+Rootelementcontainingdeclarationsoftheapplication-levelcomponentscontainedinthepackage.Thiselementcanalsoincludeglobaland/ordefaultattributesfortheapplication,suchasalabel,icon,theme,requiredpermission,etc.Quantity:0or1.
25
poweredbyanddev.org
andbook-AndroidProgramming
Youcanplace0+ofeachofthefollo
wingchildren:AnActivityistheprimarythingforanapplicationtointeractwiththeuser.Theinitialscreentheuserseeswhenlaunchinganapplicationisanactivity,andmostotherscreenstheyusewillbeimplementedasseparateactivitiesdeclaredwithadditionalactivitytags.
Note:EveryActivitymusthaveantaginthemanifestwhetheritisexposedtotheworldorintendedforuseonlywithinitsownpackage.IfanActivityhasnomatchingtaginthemanifest,youwon'tbeabletolaunchit.
Optionally,tosupportlateruntimelookup,youcaninclude1+elementstodescribetheactionstheactivitysupports.DeclareswhatkindofIntentsacomponentsupports.Inadditiontothevariouskindsofvaluesthatcanbespecifiedunderthiselement,attributescanbegivenheretosupplyauniquelabel,icon,andotherinformationfortheactionbeingdescribed.
Anaction-typethatthecomponentsupports.Example:
26
poweredbyanddev.org
andbook-AndroidProgramming
Acategory-typethatthecomponentsupports.Example:
AnMIMEtype,URIscheme,URIauthority,orURIpaththatthecomponentsupports.Youcanalsoassociate1+piecesofmetadatawithyouractivity:Addsanewpieceofmetadatatotheactivity,whichclientscanretrievethroughComponentInfo.metaData.AnIntentReceiverallowsanapplicationtobetoldaboutchangestodataoractionsthathappen,evenifitisnotcurrentlyrunning.Aswiththeactivitytag,youcanoptionallyinclude1+elementsthatthereceiversupportsorvalues,justallthesameaswith.
AServiceisacomponentthatcanruninthebackgroundforanarbitraryamountoftime.Aswiththeactivitytag,youcanoptionallyincludeoneormoreelementsthattheservicesupportsorvalues;seetheactivity'sanddescriptionsformoreinformation.27
poweredbyanddev.org
andbook-AndroidProgramming
AContentProviderisacomponentthatmanagespersistentdataandpublishesitforaccessbyotherapplications.Youcanalsooptionallyattachoneormorevalues,asdescribedintheactivity'sdescription.
Ofcourseallhave.
to
be
orclosed
28
poweredbyanddev.org
andbook-AndroidProgramming
ResourcesandthemagicR.java
TheresourcesofaprojectandtheR.javaareverycloserelated.
Resources
Resourcesareexternalfiles(non-codefiles)thatareusedbyyourcodeandcompiledintoyourapplicationatbuildtime.Androidsupportsanumberofdifferentkindsofresourcefiles,includingXML,PNG,andJPEGfiles.TheXMLfileshaveverydifferentformatsdependingonwhattheydescribe.Resourcesareexternalizedfromsourcecode,andXMLfilesarecompiledintoabinary,fastloadingformatforefficiencyreasons.String
sarecompressedintoamoreefficientstorageform.ListofresourcesResource-typesandwheretoplacethem:????layout-files?“/res/layout/”images?“/res/drawable/”animations?“/res/anim/”styles,stringsandarrays?“/res/values/”oNamesdonothavetobeexactlylike:o‘arrays.xml’todefinearrayso‘colors.xml’todefinecolors?#RGB,#ARGB,#RRGGBB,#AARRGGBBo‘dimens.xml’todefinedimensionso‘strings.xml’todefinestringso‘styles.xml’todefinestyleobjectsrawfileslikemp3sorvideos?“/res/raw/”
29
poweredbyanddev.org
andbook-AndroidProgramming
UsingresourcesincodeUsingresourcesincodeisjustamatterofknowingthefullresourceIDandwhattypeofobjectyourresourcehasbeencompiledinto.Hereisthesyntaxforreferringtoaresource:R.resource_type.resource_nameorandroid.R.resource_type.resource_nameWhereresource_typeistheRsubclassthatholdsaspecifictypeofresource.resource_nameisthenameattributeforresourcesdefinedinXMLfiles,orthefilename(withouttheextension)forresourcesdefinedbyotherfiletypes.EachtypeofresourcewillbeaddedtoaspecificRsubclass,dependingonthetypeofresourceitis.Resourcescompiledbyyourownapplicationcanbereferredtowithoutapackagename(simplyasR.resource_type.resource_name).Androidcontainsanumberofstandardresources,suchasscreenstylesandbuttonbackgrounds.Torefertotheseincode,youmustqualifythemwithandroid,asforexamplein:android.R.drawable.button_background.
30
poweredbyanddev.org
andbook-AndroidProgramming
ReferencingResourcesAvaluesuppliedinanattribute(orresource)canalsobeareferencetoanotherresource.Thisisoftenusedinlayoutfilestosupplystrings(sotheycanbelocalized)andimages(whichexistinanotherfile),thoughareferencecanbeanyresourcetypeincludingcolorsandintegers.Forexample,ifwehavecolorresources,wecanwritealayoutfilethatsetsthetextcolorsizetobethevaluecontainedinoneofthoseresources:
Noteheretheuseofthe'@'prefixtointroducearesourcereference-thetextfollowingthatisthenameofaresourceintheformof@[package:]type/name.Inthiscasewedidn'tneedtospecifythepackagebecausewearereferencingaresourceinourownpackage.Toreferenceasystemresource,youwouldneedtowrite:
Asanotherexample,youshouldalwaysuseresourcereferenceswhensupplyingstringsinalayoutfilesothattheycanbelocalized:
ght="fill_parent"android:textColor="@android:color/opaque_red"android:text="@string/hello_world"/>
31
poweredbyanddev.org
andbook-AndroidProgramming
AlternateResources&;Localization
AlternateResourcesandLocalizationisaveryusefulissueyouwillloveAndroidfor.ExpectyouwouldhavetodesignaGUIthatfitslandscapeandportraitscreen-orientationwellatthesametime–thatisalmostimpossible.YoucansupplydifferentresourcesforyourapplicationaccordingtotheUIlanguageorhardwareconfigurationofthedevice.Notethateventhoughyoucanincludedifferentstring,layout,andallotherresources,theSDKdoesnotexposemethodstoletyouspecifywhichalternateresourcesettobeused.Androiddetectsthepropersetforthehardwareandlocation,andloadsthemasappropriate.Onlytheusercanselectalternatelanguagesettingsusingthesettingspanelonthedevice.Toincludealternateresources,createparallelresourcefolderswithdash-separatedqualifiersappendedtothefoldernames,indicatingtheconfigurationitappliesto(language,screenorientation,dpi,resolution,…).Forexample,hereisaprojectdiffersbetweendiffersbetweenEnglishandGermanvalue-resources(hereonlystrings):
MyApp/res/values-en/strings.xmlvalues-de/strings.xml
Androidsupportsseveraltypesofqualifiers,withvariousvaluesforeach.Appendthesetotheendoftheresourcefoldername,separatedbydashes.Youcanaddmultiplequalifierstoeachfoldername,buttheymustappearintheordertheyarelistedhere.Forexample,afoldercontainingdrawableresourcesforafullyspecifiedconfigurationwouldlooklike:
32
poweredbyanddev.org
andbook-AndroidProgramming
MyApp/res/drawable-en-rUS-port-92dpi-finger-keyshidden-12key-dpad-480x320/
Moretypically,youwillonlyspecifyafewspecificconfigurationoptionsthataresourceisdefinedfor.Youmaydropanyofthevaluesfromthecompletelist,aslongastheremainingvaluesarestillinthesameorder:
MyApp/res/drawable-en-rUS-finger/drawable-port/drawable-port-160dpi/drawable-qwerty/
Androidwillpickwhichofthevariousunderlyingresourcefilesfitsbestduringruntime,dependingonthecurrentdevice-configuration.
ThemagicR.java
Aproject'sR.javaisanauto-generatedfileindexingalltheresourcesofyourproject.Youusethisclassinyoursourcecodeasasortofshorthandwaytorefertoresourcesyou'veincludedinyourproject.Thisisparticularlypowerfulwiththecode-completionfeaturesofIDEslikeEclipsebecauseitletsyouquicklyandinteractivelylocatethespecificreferenceyou'relookingfor.Additionallyyougaincompile-timesafetythattheresourceyouwanttousereallyexists.
33
poweredbyanddev.org
andbook-AndroidProgramming
HelloWorld–TheAndroidway.
Inthisveryfirsttutorialonewilllearnhow
tocreateanAndroidApplicationusingaXMLlayout.Keepinmindthat,usingXML-Layoutsishighlypreferable!Whatitwillfinallylooklike:
Picture6FirstAndroidApplication-Finallook(sdk-version:m5)
ButbeforeallthatoneneedstodownloadandinstalltheAndroidSDK…
34
poweredbyanddev.org
andbook-AndroidProgramming
InstallingtheAndroidSDK
ThelatestAndroidSDKforWindows,MacandLinuxcanalwaysbeobtainedfromthefollowingURI:code.google/android/download.htmlItonlyneedstobedownloadedandunzippedtoyourpreferredhddlocation.TheAndroidDevelopmentTools(ADT)AndroidprovidesanEclipseplugincalled‘ADT’tomakeprogramminganddebuggingeasier.TheADTprovideseasyaccesstotheLogCat,theAndroidManifest/Resource-Editor,File,Thread,andHeapControl,incomingcall/smssimulation,etc…–sinceSDK-versionm5allformultipleemulatorinstancesatthesametime.InstallingtheEclipsePlugin(ADT)TodownloadandinstalltheADTplugin,followthestepsGoogleprovidestodevelopers:1.StartEclipse,thenselectHelp>SoftwareUpdates>FindandInstall……2.Inthedialogthatappears,selectSearchfornewfeaturestoinstallandpressNext.3.PressNewRemoteSite.4.Intheresultingdialogbox,enteranamefortheremotesite(e.g.AndroidPlugin)andenterthisasitsURL:
https://dl-ssl.google/android/eclipse/
PressOK.5.Youshouldnowseethenewsiteaddedtothesearchlist(andchecked).PressFinish.35
poweredbyanddev.org
andbook-AndroidProgramming
6.InthesubsequentSearchResultsdialogbox,selectthecheckboxforAndroidPlugin>DeveloperTools.Thiswillcheckbothfeatures:"AndroidDeveloperTools",and"AndroidEditors".TheAndroidEditorsfeatureisoptional,butrecommended.Ifyouchoosetoinstallit,youneedtheWSTpluginmentionedearlierinthispage.
NowpressNext.
7.ReadthelicenseagreementandthenselectAccepttermsofthelicenseagreement,ifappropriate.PressNext.8.PressFinish.9.TheADTpluginisnotsigned;youcanaccepttheinstallationanywaybypressingInstallAll.10.RestartEclipse.11.Afterrestart,updateyourEclipsepreferencestopointtotheSDKdirectory:a.SelectWindow>Preferences……toopenthePreferencespanel.(MacOSX:Eclipse>Preferences)b.SelectAndroidfromtheleftpanel.c.FortheSDKLocationinthemainpanel,pressBrowse……andlocatetheSDKdirectory.d.PressApply,thenOK.UpdatingtheADTPluginUpdatingtheADTPluginfollowsthestandardprocedureofupgradingacommonEclipseplugin:1.SelectHelp>SoftwareUpdates>FindandInstall……2.SelectSearchforupdatesofthecurrentlyinstalledfeaturesandpressFinish.3.IfanyupdateforADTisavailable,selectandinstall.
36
poweredbyanddev.org
andbook-AndroidProgramming
Installationdone,let’sdoso
mecode
BeforewecanstartcodingweobviouslyhavetocreateanewAndroidProject.CreatinganewAndroidProject1.ThefirstthingthatneedstobeforeveryAndroidApplicationistocreateanewAndroidProject.Todothat,simplyopenthePackageExlporerinEclipseright-clickonsomeblankspaceandchoose:New>Project…
Picture7FirstAndroidApplication-Step1
2.Select:Android>AndroidProject
37
poweredbyanddev.org
andbook-AndroidProgramming
Picture8FirstAndroidApplication-Step2
3.Fillouttheformwithvaluesfittingyourapplicationspurpose……
Picture9FirstAndroidApplication-Step3
38
poweredbyanddev.org
andbook-AndroidProgramming
4.ThisareallthefilesforyourfirstAndroid-Application(don'tpanic,mostlyallofthemareresource-files)
Picture10FirstAndroidApplication-Step4
Huh,whatareallthatfilessupposedtodo?AsyounowhavecreatedyourfirstAndroidProjectyouwillseeabunchoffilesappearinthatnewproject.TheMainActivityYou’llseesomedefaultcodelikethefollowing,whenyounownavigateto:“/src/your_package_Structure/Hello_Android.java”
packageorg.anddev.android.Hello_Android;importandroid.app.Activity;importandroid.os.Bundle;publicclassHello_AndroidextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);/*Makethisapplicationuse*themain.xml-layout-file.*/this.setContentView(R.layout.main);}}
39
poweredbyanddev.org
andbook-AndroidProgramming
Wecouldnowimmediatelyotherfilestoo.
ourApplicationbutletmeexplainofthe
TheXML-Layout(main.xml)TheADTcreatedthisverybasicActivityforyou.AsweknowActivitiesaresomehowlikeJFramesinSwing.InAndroidweextendfromActivityandneedtooverwriteasinglefunction,calledonCreate(…).Withinthisfunctionwehavetocalli.e.setContentView(R.layout.main)whichmakesourActivityusethemain.xmlwhichwasalsocreatedbytheADT:
Wehavea‘fullscreen’verticalLinearLayout,thatcontainsasingleTextViewshowingapre-definedString.TheAndroidManifest.xmlSolet’sfacetheAndroidManifest.xml:
40
poweredbyanddev.org
andbook-AndroidProgramming
Let’ssplitthatup…Everyxml-filestartswiththefollowingline,itdefinesthexml-versionandencoding-typeofthexml-text.Justcopy-pasteittoeverynewfile.
version="1.0"encoding="utf-8"?>
Asweknowtheoutermosttagineveryxml-fileshouldcontainthisattribute:
xmlns:android="schemas.android/apk/res/android"
BecauseitmakesavarietyofgeneralAndroidattributesavailableinthefile.
……
Thetagistherootelementcontainingdeclarationsofallapplication-levelcomponentscontainedinthepackage.Thiselementcanalsoincludeglobaland/ordefaultattributesfortheapplication,suchasalabel,icon,theme,requiredpermission,etc…Herewedefinejusttheicon,bymakinga‘@-refer’toaimageplacedunder"/res/drawable/".
……
InsideofthetagweneedtodefineallActivities/IntentReceiversthatneedtobestartedviaIntents.InthiscasewehaveonlyonesimpleActivity.
……
41
poweredbyanddev.org
andbook-AndroidProgramming
Youprobablyhaverecognizesthatthepackage-attributefromthetagtogetherwiththeandroid:nameattributefromthetagalwaysresultinthecompletepackage-pathtotheActivitydescribed.TheinnermosttagisthetagwhichdefinesonwhichIntentswewanttolisten.HerewewanttheHello_AndroidActivitylaunchablefromwithintheemulatorbyclickingtheicon(thatwasdefinedinthetag).
Note:Thedebugging-processwithaAndroidApplicationisexactlythesamethanwithanormalJavaApplication.
42
poweredbyanddev.org
andbook-AndroidProgramming
RunningyourfirstapplicationNowweneedtocreatea‘-Configuration’.OpenthetheEclipsesuppermenuandClick"OpenRunDialog……"
-DropDownin
Picture11Openingtherun-dialog
Picture12Creatingarun-configuration
43
poweredbyanddev.org
andbook-AndroidProgramming
FromnowonyoucanrunyourapplicationbyclickingtheHavingdonethatyou’llseethis:
button.
Picture13FirstAndroidApplication-Theresult(sdk-versionm5)
Afterthefirstdeployyoucanalsoseeyourapplicationbeinglistedinthequick-menu,displayedwiththedefaulticon:
Picture14FirstAndroidApplication-AddedtoQuickMenu(sdk-versionm5)
44
poweredbyanddev.org
andbook-AndroidProgramming
UIstheJavaway
ThesamethingaswehavejustdonewithXML-CodecanbeachievedbyhackingsomelinesofJava-Code.Rememberhowwesetourmain.xmlastheContentViewinthexmlexample.Weaccomplishedthatbydoingthefollowing:
/*Makethisapplicationuse*themain.xml-layout-file.*/this.setContentView(R.layout.main);
Activity.setContentView(…)alsoacceptsaViewastheparameter.WewillusethattosetasimpleTextViewasourContentView.
packageorg.anddev.android.Hello_Android;im
portandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassHello_AndroidextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);/*Wewanttoviewsomeverysimpletext,*soweneedaTextViewassociatedwiththisActivity.*/TextViewtv=newTextView(this);/*PutsometexttothenewlycreatedTextView*/tv.setText("HelloAndroid-by:anddev.org\n"+"Thisissoooosimple=D");/*TellourActivitytodisplaythatTextView*/this.setContentView(tv);}}
45
poweredbyanddev.org
andbook-AndroidProgramming
System.out.println(…)?
DebugginginAndroidcannotbedoneusingSystem.out.println(…)becauseasweknowAndroidisnotrunningonanormalVMbutinsideofemulatedhardwareontheDalvikVM.(Tobehonest,itcanbedonebutisshoulddefinitelybenotyourchoice)Butdon’tworry,Androidprovidesamuchmorepowerfuldebuggingfeature–TheLogCat.TheLogCatTheLogCatisapartoftheDDMS, (DalvikDebugMonitorservice)thatprovidesamechanismforcollectingandviewingsystemdebugoutput.LogsfromvariousapplicationsandportionsofthesystemarecollectedintheLogCat,whichthencanbeviewedandfiltered.
IfyoucannotseeA,doittheBway.
Picture15OpeningtheDDMSView
UsingtheLogCatEveryAndroidlogmessagehasatagandapriorityassociatedwithit.
46
poweredbyanddev.org
andbook-AndroidProgramming
Thetagofalogmessageisashortstringindicatingthesystemcomponentfromwhichthemessageoriginates(forexample,"View"fortheviewsystem).Thepriorityisoneofthefollowingcharactervalues,orderedfromlowesttohighestpriority:?????V—Verbose(lowestpriority)D—DebugI—InfoW—WarningE—Error(highestpriority)
AsweareusingEclipsewecansimplyfilterbypriorityclickingthe“V-D-IW-E”ButtonsintheLogCatViewonecanalsoseebelow.You’lllovetheADTpluginforthatfeature,because,inthemassesofoutputthewholesystemgenerates,itisreallyhardtofindanythingwithoutfilters.
Picture16TheLogCat
Theusageinthecodeisprettysimple.Youneedtomakeasingleimport:
importandroid.util.Log;
Thenyouareabletousedebuggingstatements,likethis:
Log.d("DEBUGTAG","Mydebug-message.");
47
poweredbyanddev.org
andbook-AndroidProgramming
WhensomecriticalthingshappenedyoucanpasstheThrowable/ExceptiontoLog.e(…),togettheStackTraceprintedtotheLogCat:
try{thrownewException();}catch(Exceptione){Log.e("DEBUGTAG","Erroroccured",e);}
Note:
48
poweredbyanddev.org
andbook-AndroidProgramming
UsingIntents
AsweknowthingsneededtobedoneareexpressedbyIntents.Intentscani.e.beusedtostartotherActivities.
Starting(Su
b)Activities
Anessentialthinginthelifetimeofanapplication,thatismoresophisticatedthanaHelloWorldApplication,istostartotherActivities,especiallySubActivitites.Let’sassumethefollowingscenario:WewanttohavesomethinglikeanInputDialogwheretheusercanwriteakeywordhewantstosearchonGooglefor.SowewillcreateanewAndroidProjectaswealreadydiditbefore.ThefirstthingwewilldoistoaddasecondActivitywewillname“MySecondActivity”.Inthebeginningthecodeshalllooklikethis:
packageorg.anddev.andbook.startingsubactivities;importandroid.app.Activity;importandroid.os.Bundle;publicclassMySecondActivityextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.main);}}
49
poweredbyanddev.org
andbook-AndroidProgramming
WenowwilladdaButtontothefirstActivity.Wedothatbyalteringthemain.xml,ofcourse,andnotbyswitchingtoaJavaUI.Browseto“/res/layout/main.xml”andyouwillseecodesimilartothis:
Note:maybeEclipseopenedthemain.xmlwithitsdefaultxml-Editorwhichisnotofanyuseforus.SinceSDK-versionm5theADTpluginprovidesaResource-EditorwithSyntax-Highlighting.
Picture17OpeningtheResourceEditor
IfwewouldstarttheApplicationrightnowitwouldlooklikethis:
Picture18Layoutdefault(sdk-versionm5)
50
poweredbyanddev.org
andbook-AndroidProgramming
AswewanttohaveaButtoninourapplication,wewillhavetocomeupwithsomexml-code:
Asonecanimagine,“fill_parent”makesaViewusallspacetheparentViewprovidesand“wrap_content”usesjustasmuchlayoutspaceasitneedstodisplayitscontentcorrectly.Soourbuttonwillfillthewholescreeninwidthandwraparoundthe“OpenSearch-Dialog”wetypedfortheandroid:textattribute.Ourapplicationnowlookslikethis:
Picture19LayoutwithButton(sdk-versionm5)
Whenwenowclickthebutton–nothinghappens,ofcourse.WewillhavetoapplyaListenertobespecificanOnClickListenertoHandleclickstothisButtons.Butwait…howcanwerefertothatButtoninJavaCode?
51
poweredbyanddev.org
andbook-AndroidProgramming
FindingXML-definedViewsinJava-CodeTofindaViewthatwasdefinedinXMLwefirsthavetoaddonesinglelinetotheXML-definitionofthatView,anandroid:idattribute.Inthiscasewewillgiveittheid“btn_open_search”:
FindingthatViewinJavaCodeissameeasy.WithinanActivityyoucanusethefindViewById(intresourceID)method,togetareferencetoaViewusingtheandroid:idthathasbee
ndefinedinXML.ThesamecanbedonewithanyotherclassthatextendsView,i.e.EditText,TextView,MapView,etc…ButfindViewById(…)canonlybeusedwithViewsthatareplacedwithintheLayoutthatwasloadedtothatActivityusingsetContentView(…)!Comingbacktoourexample,weaddthefollowinginCodetoonCreate(…),rightafterthesetContentView(…):
/*FindtheButtonfromourXML-layout.*/Buttonb=(Button)this.findViewById(R.id.btn_open_search);
IfEclipsecannotfindi.e.theButton-Class,justhit‘CTRL+SHIFT+O’whatwillorganizetheimportsandautomaticallyadd(inthiscase):
importandroid.widget.Button;
52
poweredbyanddev.org
andbook-AndroidProgramming
HandlingClickstoViewsWenowrememberthatweoncewantedtomakeourbuttonclickable.ThereforewesimplysetananonymousOnClickListenertoourButton:
b.setOnClickListener(newOnClickListener(){publicvoidonClick(Viewarg0){//PlacecodetohandleButton-Clickhere.}});
Note:Eclipsemightnotrecognizethefollowingimportbyitself:
importandroid.view.View.OnClickListener;
NowwewilladdanIntenttotheonClick-EventthatwillstartourSubActivity:
/*CreateanIntenttostart*MySecondActivity.*/Intenti=newIntent(StartingSubactivities.this,MySecondActivity.class);/*SendintenttotheOStomake*itawarethatwewanttostart*MySecondActivityasaSubActivity.*/startSubActivity(i,0x1337);
ThesecondparameterofstartSubActivitycanbeanyuniqueInteger.Itwillgetusefullateron(thenwewillbeplacingitdeclaredasfinaltoourActivity),whenwewanttoretrievearesultfromtheSubActivity.
53
poweredbyanddev.org
andbook-AndroidProgramming
Ifwewouldnowrunourcodeandclickourbuttonwewouldreceivethefollowingerror-message:
Picture20ActivitynotdefinedinAndroidManifest.xml
Note:Someofthemessagesshownarereallyhelpful,readthem.
Soweneedtodefineour“MySecondActivity”intheAndroidManiufest.xmltoo.Justafterthefirsttagwewrite:
Thistimewedidnotchoose“…MAIN”forand“…LAUNCHER”forbecausethereisnoneedtoget“MySecondActivity”launchedfromoutsideofourApplication.
54
poweredbyanddev.org
andbook-AndroidProgramming
“MySecondActivity”isnowreachablethroughaclicktothebutton,butitalsoreferstoourmain.xml:
setContentView(R.layout.main);
Sowehavetocreateanadditionallayoutfilefor“MySecondActivity”.ItwillcontainasocalledEditTextwhatinSwingjargonwouldbeaTextFieldandanotherButtontoreturntoour“Main”-Activity:
Ofcoursebothneedanandroid:idthatwecanusetheinourJavaCode.NowwecanchangethesetContentViewof“MySecondActivity”to:
/*GettheEditTextfromtheXML-file.*/this.et_keyword=(EditText)this.findViewById(R.id.et_keyword);/*Getthereturn-ButtonfromtheXML-file.*/Buttonb=(Button)this.findViewById(R.id.btn_return);/*MakethatButtonhandleclickstoitself.*/b.setOnClickListener(newOnClickListener(){publicvoidonClick(Viewarg0){/*PlacecodetohandleButton-Clickhere.*/}});
55
poweredbyanddev.org
andbook-AndroidProgramming
ReturningvaluesfromSubActivitiesReturningvaluesfromSubActivitiestothecallerisalsoverysimple:
/*RetrievetheTextfromtheEditText.*/Stringkeyword=MySecondActivity.this.et_keyword.getText().toString();/*Theparameterspassedtothisfunction*willbeavailabletothecaller.*/MySecondActivity.this.setResult(1,keyword);/*OurActivityisdoneandshallbeclosed.*/MySecondActivity.this.finish();
OnecouldadditionallypassasocalledBundlebacktothecaller(whatismoreorlessaHashMap),butI’lltellyoumoreofthatsoon.ObviouslythecallerhastoreactonthefactthattheSubActivitydecidedtoreturn.Toaccomplishthat,wehavetooverrideasinglemethodcomingfromtheActivityclass.ItiscalledonActivityResult(…):
@OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Stringdata,Bundleextras){/*PlaceoutcodetoreactonActivity-Resulthere.*/super.onActivityResult(requestCode,resultCode,data,extras);}
YouprobablyrecognizedthatthefirstparameteriscalledrequestCode–yesitisthesamerequestCodethatwepassedtostartSubActivityearlier.SoifwehavemorethanoneSubActivity,wecanuserequestCodetodifferentiatewhichSubActivityhasjustreturned.
Tipp:Eclipseprovidesaveryusefulfunctionthatyou’lllearntolove,especiallyifyouareextendingabase-classandsearchformethodstooverride:
56
poweredbyanddev.org
andbook-AndroidProgramming
Picture21UsingEclipsetofindmethodstooverride
SonowwecansimplyswitchontherequestCodeandcreateanotherIntenttodotheGoogle-search.
/*CheckwhichSubActivityreturned.*(Herewehaveonlyone.)*/switch(requestCode){caseMYSECONDACTIVITY_REQUESTCODE:/*CreateanewIntentto*showtheGoogle-SearchPage*withthekeywordreturned.*/IntentwebIntent=newIntent(android.content.Intent.VIEW_ACTION,Uri.parse("google/search?q="+data));startActivity(webIntent);break;}
AsyouprobablyhaverecognizedthistimewearecreatingtheIntentanotherway.Lasttimewesaidlike:“WewanttostartXYZ.class“,butthistimewedescribewhatwewanttogetdone.WewanttoVIEWaURI(UniformResourceIndicator),whichcanbeconstructedbyusingi.e.Uri.fromParts(…).OurApplicationisnowcapableof
startinga(Sub)Activity,grabbingitsresultsandlaunchingtheBrowserusinganIntent.Buthowtopassdatatoa(Sub)Activity?
57
poweredbyanddev.org
andbook-AndroidProgramming
PassingDatato(Sub)Activities
Passingdatato(Sub)Activitiesis,onceagain,nothardtomanage.OnecanusesocalledBundles,whicharemoreorlessordinaryHashMap’sthatcantakeonlytrivialdatatypes,tocarryinformationfromoneActivitytoanother.JustrememberwherewestartedourSubActivityinthelastchapter:
/*CreateanIntenttostart*MySecondActivity.*/Intenti=newIntent(StartingSubactivities.this,MySecondActivity.class);/*SendintenttotheOStomake*itawarethatwewanttostart*MySecondActivityasaSubActivity.*/startSubActivity(i,0x1337);
Rightbetweenthesetwolines,wewillputthefollowing:
/*Createabundlewhichwillbe*attachedtotheIntent,tocarry*informationtoourSubActivity.*/Bundleb=newBundle();b.putString(MY_DEFAULTSTRING_ID,"anddev.org");/*AttachBundletoourIntent.*/i.putExtras(b);
WhereMY_DEFAULTSTRING_IDcanbeanyidentifyingStringyoucanimagine.ThereisalsoamethodIntent.putExtra(…,…)whichtakesonlyoneinformationeachcall,whichwecouldhaveusedalso.
58
poweredbyanddev.org
andbook-AndroidProgramming
NowwehavetoextractthatinformationwithinourSubActivity.EveryActivitycanaccesstheoriginalIntentitwasstartedwith,bycallinggetIntent().IftherewasaBundleattachedtotheIntentwecangrabthatbyusinggetIntent().getExtras().Inthiscasewe,wewillfilltheEditText,wheretheuserwouldtypethekeyword(s)withtheDefaultStringwepassedovertheIntent:
//…setContentView(R.layout.second);/*GettheBundlefromtheIntent*thisActivitywasstartedwith.*/Bundlebundle=getIntent().getExtras();/*Extractthedefaultkeyword*byusingthepublicIDwe*definedinthecaller.*/Stringdefault_keyword=bundle.getString(StartingSubactivities.MY_DEFAULTSTRING_ID);/*GettheEditTextfromtheXML-file.*/this.et_keyword=(EditText)this.findViewById(R.id.et_keyword);/*SetthedefaultkeywordtotheEditText.*/this.et_keyword.setText(default_keyword);/*Getthereturn-ButtonfromtheXML-file.*///…
Solet’sresumewhatyouhavelearneduptohere:?CreateansimpleApplicationusingaXMLLayout?DothesamewithaJava-basedLayout?RunAndroidApplications?UsingtheLogCatfordebuggingpurpose?UseIntentstostart(Sub)Activities?FindViewsdefinedinXMLtousetheminJavaCode?HandleClickstoViews?ReturnvaluesfromSubActivities?PassdatatoSubActivitiesusingBundlesNotbadfornow.
59
poweredbyanddev.org
andbook-AndroidProgramming
ImportantLayoutsandViewGroups
AndroidprovidesmanymoreLayoutsthanjusttheLinearLayoutweuseduptohere.ThemostimportantLayouts,e
xceptLinearLayout,youwillgettoknowcloserhereare:??RelativeLayout(Viewsareplacedrelativetoeachother)TableLayout(UsestableslikeinHTML)
AdditionallytothatIwillintroducetoyouthefollowingreallyoftenusedViewGroups:???GridView(similartoTableLayout,supports‘Adapters’)ScrollView(Ifyourcontentexceedsthescreen-size,you’llneedtoscroll)TabHost(Displayscontentintabs)
TheRelativeLayout
Accordingtoitsname,whenusingRelativeLayoutsonedefinesthepositionofViewsrelativetoother‘neighbors-Views’.
60
poweredbyanddev.org
andbook-AndroidProgramming
Bibliography
1.OpenHansetAlliance.OpenHansetAlliance.[Online]openhandsetalliance/.2.GoogleGroups.AndroidDiscussionGroups.[Online]code.google/android/groups.html.3.AlexaWebstats.TheWebInformationCompany.alexa.[Online]alexa.4.Gramlich,Nicolas.AndroidDevelopmentCommunity|AndroidTutorials.[Online]anddev.org.5.Hobbs,Zach.HelloAndroid.[Online]helloandroid/.6.Nguyen,Vincent.AndroidCommunity.[Online]androidcommunity/.7.Srinivas,Davanum.Showmethecode![Online]davanum.wordpress/.
61
poweredbyanddev.org
andbook-AndroidProgramming
Lostchapters
Thecommunities
Fromthefirstdayon,acoupleofcommunitiesarosefromthedepthoftheinternet.Themostimportantcommunity-websitetomention(dependingonAlexa-stats(3))isanddev.org(4),whichisthemostviewedTutorial/Community-BoardforGoogleAndroiduptodate.AlsowellknownaretheCommunity-Boards:helloandroid(5)andandroidcommunity(6).Lastbutdefinitelynotleasttomentionisthedavanum.wordpress-Blog(7),whichprovidedsomeveryearlysamplecodewheremanyprogrammersfoundagoodfirstsource.Somesitesweremore,somelesspromising,sosoonerorlatertheviewerspointedtheirfocustothemore-importantsiteslistedabove.
62
poweredbyanddev.org
1