版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
中英文对照外文翻译(文档含英文原文和中文翻译)Android:AProgrammer’sGuide1WhatIsAndroid1.1KeySkills&Concepts●Historyofembeddeddeviceprogramming●ExplanationofOpenHandsetAlliance●FirstlookattheAndroidhomescreenItcanbesaidthat,forawhile,traditionaldesktopapplicationdevelopershavebeenspoiled.Thisisnottosaythattraditionaldesktopapplicationdevelopmentiseasierthanotherformsofdevelopment.However,astraditionaldesktopapplicationdevelopers,wehavehadtheabilitytocreatealmostanykindofapplicationwecanimagine.IamincludingmyselfinthisgroupingbecauseIgotmystartindesktopprogramming.Oneaspectthathasmadedesktopprogrammingmoreaccessibleisthatwehavehadtheabilitytointeractwiththedesktopoperatingsystem,andthusinteractwithanyunderlyinghardware,prettyfreely(oratleastwithminimalexceptions).Thiskindoffreedomtoprogramindependently,however,hasneverreallybeenavailabletothesmallgroupofprogrammerswhodaredtoventureintothemurkywatersofcellphonedevelopment.NOTE:Irefertotwodifferentkindsofdevelopersinthisdiscussion:traditionaldesktopapplicationdevelopers,whoworkinalmostanylanguageandwhoseendproduct,applications,arebuilttorunonany“desktop”operatingsystem;andAndroiddevelopers,JavadeveloperswhodevelopfortheAndroidplatform.Thisisnotforthepurposesofsayingoneisbyanymeansbetterorworsethantheother.Rather,thedistinctionismadeforpurposesofcomparingthedevelopmentstylesandtoolsofdesktop
operating
system
environments
to
the
mobile
operating
system
environment1.2BriefHistoryofEmbeddedDeviceProgrammingForalongtime,cellphonedeveloperscomprisedasmallsectofaslightlylargergroupofdevelopersknownasembeddeddevicedevelopers.Seenasaless“glamorous”siblingtodesktop—andlaterweb—development,embeddeddevicedevelopmenttypicallygottheproverbialshortendofthestickasfarashardwareandoperatingsystemfeatures,becauseembeddeddevicemanufacturerswerenotoriouslystingyonfeaturesupport.Embeddeddevicemanufacturerstypicallyneededtoguardtheirhardwaresecretsclosely,sotheygaveembeddeddevicedevelopersfewlibrariestocallwhentryingtointeractwithaspecificdevice.Embeddeddevicesdifferfromdesktopsinthatanembeddeddeviceistypicallya“computeronachip.”Forexample,consideryourstandardtelevisionremotecontrol;itisnotreallyseenasanoverwhelmingachievementoftechnologicalcomplexity.Whenanybuttonispressed,achipinterpretsthesignalinawaythathasbeenprogrammedintothedevice.Thisallowsthedevicetoknowwhattoexpectfromtheinputdevice(keypad),andhowtorespondtothosecommands(forexample,turnonthetelevision).Thisisasimpleformofembeddeddeviceprogramming.However,believeitornot,simpledevicessuchasthesearedefinitelyrelatedtotherootsofearlycellphonedevicesanddevelopment.Mostembeddeddevicesran(andinsomecasesstillrun)proprietaryoperatingsystems.Thereasonforchoosingtocreateaproprietaryoperatingsystemratherthanuseanyconsumersystemwasreallyaproductofnecessity.Simpledevicesdidnotneedveryrobustandoptimizedoperatingsystems.Asaproductofdeviceevolution,manyofthemorecomplexembeddeddevices,suchasearlyPDAs,householdsecuritysystems,andGPSs,movedtosomewhatstandardizedoperatingsystemplatformsaboutfiveyearsago.Small-footprintoperatingsystemssuchasLinux,orevenanembeddedversionofMicrosoftWindows,havebecomemoreprevalentonmanyembeddeddevices.Aroundthistimeindeviceevolution,cellphonesbranchedfromotherembeddeddevicesontotheirownpath.Thisbranchingisevidentwhenyouexaminetheirarchitecture.Nearlysincetheirinception,cellphoneshavebeenfringedevicesinsofarastheyrunonproprietarysoftware—softwarethatisownedandcontrolledbythemanufacturer,andisalmostalwaysconsideredtobea“closed”system.Thepracticeofmanufacturersusingproprietaryoperatingsystemsbeganmoreoutofnecessitythananyotherreason.Thatis,cellphonemanufacturerstypicallyusedhardwarethatwascompletelydevelopedin-house,oratleasthardwarethatwasspecificallydevelopedforthepurposesofrunningcellphoneequipment.Asaresult,therewerenoopenlyavailable,off-the-shelfsoftwarepackagesorsolutionsthatwouldreliablyinteractwiththeirhardware.Sincethemanufacturersalsowantedtoguardverycloselytheirhardwaretradesecrets,someofwhichcouldberevealedbyallowingaccesstothesoftwarelevelofthedevice,thecommonpracticewas,andinmostcasesstillis,tousecompletelyproprietaryandclosedsoftwaretoruntheirdevices.Thedownsidetothisisthatanyonewhowantedtodevelopapplicationsforcellphonesneededtohaveintimateknowledgeoftheproprietaryenvironmentwithinwhichitwastorun.Thesolutionwastopurchaseexpensivedevelopmenttoolsdirectlyfromthemanufacturer.Thisisolatedmanyofthe“homebrew”developers.NOTE:Agrowingcultureofhomebrewdevelopershasembracedcellphoneapplicationdevelopment.Theterm“homebrew”referstothefactthatthesedeveloperstypicallydonotworkforacellphonedevelopmentcompanyandgenerallyproducesmall,one-offproductsontheirowntime.Another,morecompelling“necessity”thatkeptcellphonedevelopmentoutofthehandsoftheeverydaydeveloperwasthehardwaremanufacturers’solutiontothe“memoryversusneed”dilemma.Untilrecently,cellphonesdidlittlemorethanexecuteandreceivephonecalls,trackyourcontacts,andpossiblysendandreceiveshorttextmessages;notreallythe“Swissarmyknives”oftechnologytheyaretoday.Evenaslateas2002,cellphoneswithcameraswerenotcommonlyfoundinthehandsofconsumers.By1997,smallapplicationssuchascalculatorsandgames(Tetris,forexample)crepttheirwayontocellphones,buttheoverwhelmingfunctionwasstillthatofaphonedialeritself.Cellphoneshadnotyetbecomethemultiuse,multifunctionpersonaltoolstheyaretoday.NooneyetsawtheneedforInternetbrowsing,MP3playing,oranyofthemultitudesoffunctionsweareaccustomedtousingtoday.Itispossiblethatthecellphonemanufacturersof1997didnotfullyperceivetheneedconsumerswouldhaveforanall-in-onedevice.However,eveniftheneedwaspresent,alackofdevicememoryandstoragecapacitywasanevenbiggerobstacletoovercome.Morepeoplemayhavewantedtheirdevicestobeall-in-onetools,butmanufacturersstillhadtoclimbthememoryhurdle.Toputtheproblemsimply,ittakesmemorytostoreandrunapplicationsonanydevice,cellphonesincluded.Cellphones,asadevice,untilrecentlydidnothavetheamountofmemoryavailabletothemthatwouldfacilitatetheinclusionof“extra”programs.Withinthelasttwoyears,thepriceofmemoryhasreachedverylowlevels.Devicemanufacturersnowhavetheabilitytoincludemorememoryatlowerprices.ManycellphonesnowhavemorestandardmemorythantheaveragePChadinthemid-1990s.So,nowthatwehavetheneed,andthememory,wecanalljumpinanddevelopcoolapplicationsforcellphonesaroundtheworld,right?Notexactly.Devicemanufacturersstillcloselyguardtheoperatingsystemsthatrunontheirdevices.WhileafewhaveopeneduptothepointwheretheywillallowsomeJava-basedapplicationstorunwithinasmallenvironmentonthephone,manydonotallowthis.EventhesystemsthatdoallowsomeJavaappstorundonotallowthekindofaccesstothe“core”systemthatstandarddesktopdevelopersareaccustomedtohaving.1.3OpenHandsetAllianceandAndroidThisbarriertoapplicationdevelopmentbegantocrumbleinNovemberof2007whenGoogle,undertheOpenHandsetAlliance,releasedAndroid.TheOpenHandsetAllianceisagroupofhardwareandsoftwaredevelopers,includingGoogle,NTTDoCoMo,SprintNextel,andHTC,whosegoalistocreateamoreopencellphoneenvironment.Thefirstproducttobereleasedundertheallianceisthemobiledeviceoperatingsystem,Android.WiththereleaseofAndroid,Googlemadeavailableahostofdevelopmenttoolsandtutorialstoaidwould-bedevelopersontothenewsystem.Helpfiles,theplatformsoftwaredevelopmentkit(SDK),andevenadevelopers’communitycanbefoundatGoogle’sAndroidwebsite,Thissiteshouldbeyourstartingpoint,andIhighlyencourageyoutovisitthesite.NOTE:Google,inpromotingthenewAndroidoperatingsystem,evenwentasfarastocreatea$10millioncontestlookingfornewandexcitingAndroidapplications.WhilecellphonesrunningLinux,Windows,andevenPalmOSareeasytofind,asofthiswriting,nohardwareplatformshavebeenannouncedforAndroidtorunon.HTC,LGElectronics,Motorola,andSamsungaremembersoftheOpenHandsetAlliance,underwhichAndroidhasbeenreleased,sowecanonlyhopethattheyhaveplansforafewAndroid-baseddevicesinthenearfuture.WithitsreleaseinNovember2007,thesystemitselfisstillinasoftware-onlybeta.Thisisgoodnewsfordevelopersbecauseitgivesusarareadvancelookatafuturesystemandachancetobegindevelopingapplicationsthatwillrunassoonasthehardwareisreleased.NOTE:ThisstrategyclearlygivestheOpenHandsetAllianceabigadvantageoverothercellphoneoperatingsystemdevelopers,becausetherecouldbeanuncountablenumberofapplicationsavailableimmediatelyforthefirstdevicesreleasedtorunAndroid.IntroductiontoAndroidAndroid,asasystem,isaJava-basedoperatingsystemthatrunsontheLinux2.6kernel.Thesystemisverylightweightandfullfeatured.AndroidapplicationsaredevelopedusingJavaandcanbeportedrathereasilytothenewplatform.IfyouhavenotyetdownloadedJavaorareunsureaboutwhichversionyouneed,IdetailtheinstallationofthedevelopmentenvironmentinChapter2.OtherfeaturesofAndroidincludeanaccelerated3-Dgraphicsengine(basedonhardwaresupport),databasesupportpoweredbySQLite,andanintegratedwebbrowser.IfyouarefamiliarwithJavaprogrammingorareanOOPdeveloperofanysort,youarelikelyusedtoprogrammaticuserinterface(UI)development—thatis,UIplacementwhichishandleddirectlywithintheprogramcode.Android,whilerecognizingandallowingforprogrammaticUIdevelopment,alsosupportsthenewer,XML-basedUIlayout.XMLUIlayoutisafairlynewconcepttotheaveragedesktopdeveloper.IwillcoverboththeXMLUIlayoutandtheprogrammaticUIdevelopmentinthesupportingchaptersofthisbook.OneofthemoreexcitingandcompellingfeaturesofAndroidisthat,becauseofitsarchitecture,third-partyapplications—includingthosethatare“homegrown”—areexecutedwiththesamesystempriorityasthosethatarebundledwiththecoresystem.Thisisamajordeparturefrommostsystems,whichgiveembeddedsystemappsagreaterexecutionprioritythanthethreadpriorityavailabletoappscreatedbythird-partydevelopers.Also,eachapplicationisexecutedwithinitsownthreadusingaverylightweightvirtualmachine.AsidefromtheverygenerousSDKandthewell-formedlibrariesthatareavailabletoustodevelopwith,themostexcitingfeatureforAndroiddevelopersisthatwenowhaveaccesstoanythingtheoperatingsystemhasaccessto.Inotherwords,ifyouwanttocreateanapplicationthatdialsthephone,youhaveaccesstothephone’sdialer;ifyouwanttocreateanapplicationthatutilizesthephone’sinternalGPS(ifequipped),youhaveaccesstoit.Thepotentialfordeveloperstocreatedynamicandintriguingapplicationsisnowwideopen.OntopofallthefeaturesthatareavailablefromtheAndroidsideoftheequation,Googlehasthrowninsomeverytantalizingfeaturesofitsown.DevelopersofAndroidapplicationswillbeabletotietheirapplicationsintoexistingGoogleofferingssuchasGoogleMapsandtheomnipresentGoogleSearch.SupposeyouwanttowriteanapplicationthatpullsupaGooglemapofwhereanincomingcallisemanatingfrom,oryouwanttobeabletostorecommonsearchresultswithyourcontacts;thedoorsofpossibilityhavebeenflungwideopenwithAndroid.Chapter2beginsyourjourneytoAndroiddevelopment.Youwilllearnthehow’sandwhy’sofusingspecificdevelopmentenvironmentsorintegrateddevelopmentenvironments(IDE),andyouwilldownloadandinstalltheJavaIDEEclipse.2Application:HelloWorld2.1KeySkills&Concepts● CreatingnewAndroidprojects● WorkingwithViews● UsingaTextView● Modifyingthemain.xmlfile● RunningapplicationsontheAndroidEmulatorInthischapter,youwillbecreatingyourfirstAndroidActivity.Thischapterexaminestheapplication-buildingprocessfromstarttofinish.IwillshowyouhowtocreateanAndroidprojectinEclipse,addcodetotheinitialfiles,andrunthefinishedapplicationintheAndroidEmulator.TheresultingapplicationwillbeafullyfunctioningprogramrunninginanAndroidenvironment.Actually,asyoumovethroughthischapter,youwillbecreatingmorethanoneAndroidActivity.ComputerprogrammingtraditiondictatesthatyourfirstapplicationbethetypicalHelloWorld!application,sointhefirstsectionyouwillcreateastandardHelloWorld!applicationwithjustablankbackgroundandthe“HelloWorld!”text.Then,forthesakeofenablingyoutogettoknowthelanguagebetter,thenextsectionexplainsindetailthefilesautomaticallycreatedbyAndroidforyourHelloWorld!application.YouwillcreatetwoiterationsofthisActivity,eachusingdifferenttechniquesfordisplayinginformationtothescreen.YouwillalsocreatetwodifferentversionsofaHelloWorld!applicationthatwilldisplayanimagethatdeliversthe“HelloWorld!”message.ThiswillgiveyouagoodintroductiontothecontrolsandinnerworkingsofAndroid.NOTE:Youwilloftensee“application”and“Activity”usedinterchangeably.ThedifferencebetweenthetwoisthatanapplicationcanbecomposedofmultipleActivities,butoneapplicationmusthaveatleastoneActivity.Each“window”orscreenofyourapplicationisaseparateActivity.Therefore,ifyoucreateafairlysimpleapplicationwithonlyonescreenofdata(liketheHelloWorld!applicationinthischapter),thatwillbeoneActivity.InfuturechaptersyouwillcreateapplicationswithmultipleActivities.TomakesurethatyougetagoodoveralllookatprogramminginAndroid,inChapter6youwillcreatebothoftheseapplicationsintheAndroidSDKcommand-lineenvironmentforMicrosoftWindowsandLinux.Inotherwords,thischaptercoversthecreationprocessinEclipse,andChapter6coversthecreationprocessusingthecommand-linetools.Therefore,beforecontinuing,youshouldcheckthatyourEclipseenvironmentiscorrectlyconfigured.ReviewthestepsinChapter3forsettingthePATHstatementfortheAndroidSDK.YoushouldalsoensurethattheJREiscorrectlyinyourPATHstatement.TIP:Ifyouhaveconfiguration-relatedissueswhileattemptingtoworkwithanyofthecommand-lineexamples,tryreferringtotheconfigurationstepsinChapters2and3;andlookattheAndroidSDKdocumentation.2.2CreatingYourFirstAndroidProjectinEclipseTostartyourfirstAndroidproject,openEclipse.WhenyouopenEclipseforthefirsttime,itopenstoanemptydevelopmentenvironment(seeFigure5-1),whichiswhereyouwanttobegin.Yourfirsttaskistosetupandnametheworkspaceforyourapplication.ChooseFile|New|AndroidProject,whichwilllaunchtheNewAndroidProjectwizard.CAUTIONDonotselectJavaProjectfromtheNewmenu.WhileAndroidapplicationsarewritteninJava,andyouaredoingallofyourdevelopmentinJavaprojects,thisoptionwillcreateastandardJavaapplication.SelectingAndroidProjectenablesyoutocreateAndroid-specificapplications.IfyoudonotseetheoptionforAndroidProject,thisindicatesthattheAndroidpluginforEclipsewasnotfullyorcorrectlyinstalled.ReviewtheprocedureinChapter3forinstallingtheAndroidpluginforEclipsetocorrectthis.2.3TheNewAndroidProjectwizardcreatestwothingsforyouAshellapplicationthattiesintotheAndroidSDK,usingtheandroid.jarfile,andtiestheprojectintotheAndroidEmulator.ThisallowsyoutocodeusingalloftheAndroidlibrariesandpackages,andalsoletsyoudebugyourapplicationsintheproperenvironment.Yourfirstshellfilesforthenewproject.Theseshellfilescontainsomeofthevitalapplicationblocksuponwhichyouwillbebuildingyourprograms.InmuchthesamewayascreatingaMicrosoft.NETapplicationinVisualStudiogeneratessomeWindows-createdprogramcodeinyourfiles,usingtheAndroidProjectwizardinEclipsegeneratesyourinitialprogramfilesandsomeAndroid-createdcode.Inaddition,theNewAndroidProjectwizardcontainsafewoptions,shownnext,thatyoumustsettoinitiateyourAndroidproject.FortheProjectNamefield,forpurposesofthisexample,usethetitleHelloWorldText.ThisnamesufficientlydistinguishesthisHelloWorld!projectfromtheothersthatyouwillbecreatinginthischapter.IntheContentsarea,keepthedefaultselections:theCreateNewProjectinWorkspaceradiobuttonshouldbeselectedandtheUseDefaultLocationcheckboxshouldbechecked.ThiswillallowEclipsetocreateyourprojectinyourdefaultworkspacedirectory.Theadvantageofkeepingthedefaultoptionsisthatyourprojectsarekeptinacentrallocation,whichmakesordering,managing,andfindingtheseprojectsquiteeasy.Forexample,ifyouareworkinginaUnix-basedenvironment,thispathpointstoyour$HOMEdirectory.IfyouareworkinginaMicrosoftWindowsenvironment,theworkspacepathwillbeC:/Users/<username>/workspace,asshowninthepreviousillustration.However,foranynumberofreasons,youmaywanttounchecktheUseDefaultLocationcheckboxandselectadifferentlocationforyourproject.OnereasonyoumaywanttospecifyadifferentlocationhereissimplyifyouwanttochoosealocationforthisspecificprojectthatisseparatefromotherAndroidprojects.Forexample,youmaywanttokeeptheprojectsthatyoucreateinthisbookinadifferentlocationfromprojectsthatyoucreateinthefutureonyourown.Ifso,simplyoverridetheLocationoptiontospecifyyourowncustomlocationdirectoryforthisproject.3ApplicationFundamentalsAndroidapplicationsarewrittenintheJavaprogramminglanguage.ThecompiledJavacode—alongwithanydataandresourcefilesrequiredbytheapplication—isbundledbytheaapttoolintoanAndroidpackage,anarchivefilemarkedbyan.apksuffix.Thisfileisthevehiclefordistributingtheapplicationandinstallingitonmobiledevices;it'sthefileusersdownloadtotheirdevices.Allthecodeinasingle.apkfileisconsideredtobeoneapplication.Inmanyways,eachAndroidapplicationlivesinitsownworld:1.Bydefault,everyapplicationrunsinitsownLinuxprocess.Androidstartstheprocesswhenanyoftheapplication'scodeneedstobeexecuted,andshutsdowntheprocesswhenit'snolongerneededandsystemresourcesarerequiredbyotherapplications.2.Eachprocesshasitsownvirtualmachine(VM),soapplicationcoderunsinisolationfromthecodeofallotherapplications.3.Bydefault,eachapplicationisassignedauniqueLinuxuserID.Permissionsaresetsothattheapplication'sfilesarevisibleonlytothatuserandonlytotheapplicationitself—althoughtherearewaystoexportthemtootherapplicationsaswell.It'spossibletoarrangefortwoapplicationstosharethesameuserID,inwhichcasetheywillbeabletoseeeachother'sfiles.Toconservesystemresources,applicationswiththesameIDcanalsoarrangetoruninthesameLinuxprocess,sharingthesameVM.3.1ApplicationComponentsAcentralfeatureofAndroidisthatoneapplicationcanmakeuseofelementsofotherapplications(providedthoseapplicationspermitit).Forexample,ifyourapplicationneedstodisplayascrollinglistofimagesandanotherapplicationhasdevelopedasuitablescrollerandmadeitavailabletoothers,youcancalluponthatscrollertodothework,ratherthandevelopyourown.Applicationhavefourtypesofcomponents:(1)ActivitiesAnactivitypresentsavisualuserinterfaceforonefocusedendeavortheusercanundertake.Forexample,anactivitymightpresentalistofmenuitemsuserscanchoosefromoritmightdisplayphotographsalongwiththeircaptions.Atextmessagingapplicationmighthaveoneactivitythatshowsalistofcontactstosendmessagesto,asecondactivitytowritethemessagetothechosencontact,andotheractivitiestoreviewoldmessagesorchangesettings.Thoughtheyworktogethertoformacohesiveuserinterface,eachactivityisindependentoftheothers.EachoneisimplementedasasubclassoftheActivitybaseclass.Anapplicationmightconsistofjustoneactivityor,likethetextmessagingapplicationjustmentioned,itmaycontainseveral.Whattheactivitiesare,andhowmanytherearedepends,ofcourse,ontheapplicationanditsdesign.Typically,oneoftheactivitiesismarkedasthefirstonethatshouldbepresentedtotheuserwhentheapplicationislaunched.Movingfromoneactivitytoanotherisaccomplishedbyhavingthecurrentactivitystartthenextone.Eachactivityisgivenadefaultwindowtodrawin.Typically,thewindowfillsthescreen,butitmightbesmallerthanthescreenandfloatontopofotherwindows.Anactivitycanalsomakeuseofadditionalwindows—forexample,apop-updialogthatcallsforauserresponseinthemidstoftheactivity,orawindowthatpresentsuserswithvitalinformationwhentheyselectaparticularitemon-screen.Thevisualcontentofthewindowisprovidedbyahierarchyofviews—objectsderivedfromthebaseViewclass.Eachviewcontrolsaparticularrectangularspacewithinthewindow.Parentviewscontainandorganizethelayoutoftheirchildren.Leafviews(thoseatthebottomofthehierarchy)drawintherectanglestheycontrolandrespondtouseractionsdirectedatthatspace.Thus,viewsarewheretheactivity'sinteractionwiththeusertakesplace.Forexample,aviewmightdisplayasmallimageandinitiateanactionwhentheusertapsthatimage.Androidhasanumberofready-madeviewsthatyoucanuse—includingbuttons,textfields,scrollbars,menuitems,checkboxes,andmore.Aviewhierarchyisplacedwithinanactivity'swindowbytheActivity.setContentView()method.ThecontentviewistheViewobjectattherootofthehierarchy.(SeetheseparateUserInterfacedocumentformoreinformationonviewsandthehierarchy.)(2)ServicesAservicedoesn'thaveavisualuserinterface,butratherrunsinthebackgroundforanindefiniteperiodoftime.Forexample,aservicemightplaybackgroundmusicastheuserattendstoothermatters,oritmightfetchdataoverthenetworkorcalculatesomethingandprovidetheresulttoactivitiesthatneedit.EachserviceextendstheServicebaseclass.Aprimeexampleisamediaplayerplayingsongsfromaplaylist.Theplayerapplicationwouldprobablyhaveoneormoreactivitiesthatallowtheusertochoosesongsandstartplayingthem.However,themusicplaybackitselfwouldnotbehandledbyanactivitybecauseuserswillexpectthemusictokeepplayingevenaftertheyleavetheplayerandbeginsomethingdifferent.Tokeepthemusicgoing,themediaplayeractivitycouldstartaservicetoruninthebackground.Thesystemwouldthenkeepthemusicplaybackservicerunningevenaftertheactivitythatstarteditleavesthescreen.It'spossibletoconnectto(bindto)anongoingservice(andstarttheserviceifit'snotalreadyrunning).Whileconnected,youcancommunicatewiththeservicethroughaninterfacethattheserviceexposes.Forthemusicservice,thisinterfacemightallowuserstopause,rewind,stop,andrestarttheplayback.Likeactivitiesandtheothercomponents,servicesruninthemainthreadoftheapplicationprocess.Sothattheywon'tblockothercomponentsortheuserinterface,theyoftenspawnanotherthreadfortime-consumingtasks(likemusicplayback).SeeProcessesandThreads,later.(3)BroadcastreceiversAbroadcastreceiverisacomponentthatdoesnothingbutreceiveandreacttobroadcastannouncements.Manybroadcastsoriginateinsystemcode—forexample,announcementsthatthetimezonehaschanged,thatthebatteryislow,thatapicturehasbeentaken,orthattheuserchangedalanguagepreference.Applicationscanalsoinitiatebroadcasts—forexample,toletotherapplicationsknowthatsomedatahasbeendownloadedtothedeviceandisavailableforthemtouse.Anapplicationcanhaveanynumberofbroadcastreceiverstorespondtoanyannouncementsitconsidersimportant.AllreceiversextendtheBroadcastReceiverbaseclass.Broadcastreceiversdonotdisplayauserinterface.However,theymaystartanactivityinresponsetotheinformationtheyreceive,ortheymayusetheNotificationManagertoalerttheuser.Notificationscangettheuser'sattentioninvariousways—flashingthebacklight,vibratingthedevice,playingasound,andsoon.Theytypicallyplaceapersistenticoninthestatusbar,whichuserscanopentogetthemessage.(4)ContentprovidersAcontentprovidermakesaspecificsetoftheapplication'sdataavailabletootherapplications.Thedatacanbestoredinthefilesystem,inanSQLitedatabase,orinanyothermannerthatmakessense.ThecontentproviderextendstheContentProviderbaseclasstoimplementastandardsetofmethodsthatenableotherapplicationstoretrieveandstoredataofthetypeitcontrols.However,applicationsdonotcallthesemethodsdirectly.RathertheyuseaContentResolverobjectandcallitsmethodsinstead.AContentResolvercantalktoanycontentprovider;itcooperateswiththeprovidertomanageanyinterprocesscommunicationthat'sinvolved.SeetheseparateContentProvidersdocumentformoreinformationonusingcontentproviders.Wheneverthere'sarequestthatshouldbehandledbyaparticularcomponent,Androidmakessurethattheapplicationprocessofthecomponentisrunning,startingitifnecessary,andthatanappropriateinstanceofthecomponentisavailable,creatingtheinstanceifnecessary.3.2Activatingcomponents:intentsContentprovidersareactivat
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 设计合同终止解除合同注意事项
- 招标木门产品研发
- 大型建筑项目水泥砖采购合同
- 中介服务合同中的客户义务与责任
- 国外工程劳务分包合同的风险评估
- 承诺一生一世的好老公
- 样品采购合同的标准格式
- 服务外包合同协议范本案例示例
- 药品购销合同的技术转让条件
- 劳务合同与服务合同的差异和对比
- 2024-2025学年高中政治《人民代表大会:国家的权力机关》教学设计
- 石材供货计划措施
- 2024年江苏省扬州市中考道德与法治真题(含解析)
- 2024-2030年中国光学级涂料行业市场发展趋势与前景展望战略分析报告
- 2024年国开电大 高级财务会计 形考任务4答案
- 【良品铺子成本控制中存在的问题及优化建议探析(定量论文)11000字】
- DB11∕T 1580-2018 生产经营单位安全生产应急资源调查规范
- 2024年浙江省气象部门招聘应届毕业生63人历年(高频重点复习提升训练)共500题附带答案详解
- 茅台酒销售合作协议
- 人教版五年级上册小数除法竖式计算练习200道及答案
- 5国家机构有哪些 第二课时(教学设计)部编版道德与法治六年级上册
评论
0/150
提交评论