版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
中英文對(duì)照外文翻譯(文檔含英文原文和中文翻譯)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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 皖西學(xué)院《大學(xué)美育實(shí)踐》2023-2024學(xué)年第一學(xué)期期末試卷
- 靈犀房屋租賃合同范例
- 府城租房合同范例
- 商務(wù)運(yùn)營(yíng)培訓(xùn)合同范例
- 山地帳篷租用合同范例
- 招標(biāo)項(xiàng)目采購(gòu)合同范例
- 昌吉物業(yè)合同范例
- 煤礦供電合同范例
- 二手房電子合同范例
- 涂料配送服務(wù)合同范例
- 2024年單位內(nèi)部治安保衛(wèi)制度(五篇)
- 2023-2024學(xué)年新疆喀什地區(qū)巴楚縣九年級(jí)(上)期末物理試卷
- 人教版(2024新版)七年級(jí)上冊(cè)生物全冊(cè)知識(shí)點(diǎn)復(fù)習(xí)提綱填空練習(xí)版(無(wú)答案)
- 孤獨(dú)癥兒童問(wèn)題行為課件
- 非ST段抬高型急性冠脈綜合征診斷和治療指南(2024)解讀
- 2024年度北京市安全員之B證(項(xiàng)目負(fù)責(zé)人)基礎(chǔ)試題庫(kù)和答案要點(diǎn)
- 2024內(nèi)蒙古匯能煤化工限公司招聘300人高頻難、易錯(cuò)點(diǎn)500題模擬試題附帶答案詳解
- 河北省邯鄲市(2024年-2025年小學(xué)四年級(jí)語(yǔ)文)人教版期末考試((上下)學(xué)期)試卷及答案
- 2024-2030年中國(guó)嵌入式多媒體卡(eMMC)行業(yè)市場(chǎng)發(fā)展趨勢(shì)與前景展望戰(zhàn)略分析報(bào)告
- 矯直機(jī)市場(chǎng)洞察報(bào)告
- 車用LNG氣瓶技術(shù)參數(shù)規(guī)格及配車選型技術(shù)資料
評(píng)論
0/150
提交評(píng)論