物联网工程中英文对照外文翻译文献_第1页
物联网工程中英文对照外文翻译文献_第2页
物联网工程中英文对照外文翻译文献_第3页
物联网工程中英文对照外文翻译文献_第4页
物联网工程中英文对照外文翻译文献_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

中英文对照外文翻译(文档含英文原文和中文翻译)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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论