




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、英语原文AndroidApplicationFundamentalsAndroidapplicationsarewrittenintheJavaprogramminglanguage.TheAndroidSDKtoolscompilethecodealongwithanydataandresourcefiles-intoanAndroidpackageanarchivean.apksuffix.Allthecodeinasingle.apkconsideredtobeoneapplicationandistheAndroid-powereddevicesusetoinstalltheappli
2、cation.Onceinstalledonadevice,eachAndroidapplicationlivesinitsownsecuritysandbox:TheAndroidoperatingsystemisamulti-userLinuxsysteminwhicheachapplicationisadifferentuser.Bydefault,thesystemassignseachapplicationauniqueLinuxuserID(theIDisusedonlybythesystemandisunknowntotheapplication).Thesystemsetspe
3、rmissionsforallthefilesinanapplicationsothatonlytheuserIDassignedtothatapplicationcanaccessthem.Eachprocesshasitsownvirtualmachine(VM),soanapplicationscoderunsinisolationfromotherapplications.Bydefault,everyapplicationrunsinitsownLinuxprocess.Androidstartstheprocesswhenanyoftheapplicationscomponents
4、needtobeexecuted,thenshutsdowntheprocesswhenitsnolongerneededorwhenthesystemmustrecovermemoryforotherapplications.Inthisway,theAndroidsystemimplementstheprincipleofleastprivilege.Thatis,eachapplication,bydefault,hasaccessonlytothecomponentsthatitrequirestodoitsworkandnomore.Thiscreatesaverysecureenv
5、ironmentinwhichanapplicationcannotaccesspartsofthesystemforwhichitisnotgivenpermission.However,therearewaysforanapplicationtosharedatawithotherapplicationsandforanapplicationtoaccesssystemservices:ItspossibletoarrangefortwoapplicationstosharethesameLinuxuserID,inwhichcasetheyareabletoaccesseachother
6、sfiles.Toconservesystemresources,applicationswiththesameuserIDcanalsoarrangetoruninthesameLinuxprocessandsharethesameVM(theapplicationsmustalsobesignedwiththesamecertificate).Anapplicationcanrequestpermissiontoaccessdevicedatasuchastheuserscontacts,SMSmessages,themountablestorage(SDcard),camera,Blue
7、tooth,andmore.Allapplicationpermissionsmustbegrantedbytheuseratinstalltime.ThatcoversthebasicsregardinghowanAndroidapplicationexistswithinthesystem.Therestofthisdocumentintroducesyouto:Thecoreframeworkcomponentsthatdefineyourapplication.Themanifestwhichyoudeclarecomponentsandrequireddevicefeaturesfo
8、ryourapplication.Resourcesthatareseparatefromtheapplicationcodeandallowyourapplicationtogracefullyoptimizeitsbehaviorforavarietyofdeviceconfigurations.ApplicationComponentsApplicationcomponentsaretheessentialbuildingblocksofanAndroidapplication.Eachcomponentisadifferentpointthroughwhichthesystemcane
9、nteryourapplication.Notallcomponentsareactualentrypointsfortheuserandsomedependoneachother,buteachoneexistsasitsownentityandplaysaspecificrole-eachoneisauniquebuildingblockthathelpsdefineyourapplicationsoverallbehavior.Therearefourdifferenttypesofapplicationcomponents.Eachtypeservesadistinctpurposea
10、ndhasadistinctlifecyclethatdefineshowthecomponentiscreatedanddestroyed.Herearethefourtypesofapplicationcomponents:ActivitiesAnactivityrepresentsasinglescreenwithauserinterface.Forexample,anemailapplicationmighthaveoneactivitythatshowsalistofnewemails,anotheractivitytocomposeanemail,andanotheractivit
11、yforreadingemails.Althoughtheactivitiesworktogethertoformacohesiveuserexperienceintheemailapplication,eachoneisindependentoftheothers.Assuch,adifferentapplicationcanstartanyoneoftheseactivities(iftheemailapplicationallowsit).Forexample,acameraapplicationcanstarttheactivityintheemailapplicationthatco
12、mposesnewmail,inorderfortheusertoshareapicture.AnactivityisimplementedasasubclassoActivityandyoucanlearnmoreaboutitintheActivitiesdeveloperguide.ServicesAserviceisacomponentthatrunsinthebackgroundtoperformlong-runningoperationsortoperformworkforremoteprocesses.Aservicedoesnotprovideauserinterface.Fo
13、rexample,aservicemightplaymusicinthebackgroundwhiletheuserisinadifferentapplication,oritmightfetchdataoverthenetworkwithoutblockinguserinteractionwithanactivity.Anothercomponent,suchasanactivity,canstarttheserviceandletitrunorbindtoitinordertointeractwithit.AserviceisimplementedasasubclassofServicea
14、ndyoucanlearnmoreaboutitintheServicesdeveloperguide.ContentprovidersAcontentprovidermanagesasharedsetofapplicationdata.Youcanstorethedatainthe,anSQLitedatabase,ontheweb,oranyotherpersistentstoragelocationyourapplicationcanaccess.Throughthecontentprovider,otherapplicationscanqueryorevenmodifythedata(
15、ifthecontentproviderallowsit).Forexample,theAndroidsystemprovidesacontentproviderthatmanagestheuserscontactinformation.Assuch,anyapplicationwiththeproperpermissionscanquerypartofthecontentprovider(suchasContactsContract.Datatoreadandwriteinformationaboutaparticularperson.Contentprovidersarealsousefu
16、lforreadingandwritingdatathatisprivatetoyourapplicationandnotshared.Forexample,theNotePadsampleapplicationusesacontentprovidertosavenotes.AcontentproviderisimplementedasasubclassofContentProviderandmustimplementastandardsetofAPIsthatenableotherapplicationstoperformtransactions.Formoreinformation,see
17、theContentProvidersdeveloperguide.BroadcastreceiversAbroadcastreceiverisacomponentthatrespondstosystem-widebroadcastannouncements.Manybroadcastsoriginatefromthesystemforexample,abroadcastannouncingthatthescreenhasturnedoff,thebatteryislow,orapicturewascaptured.Applicationscanalsoinitiatebroadcasts-f
18、orexample,toletotherapplicationsknowthatsomedatahasbeendownloadedtothedeviceandisavailableforthemtouse.Althoughbroadcastreceiversdontdisplayauserinterface,theymaycreateastatusbarnotificationtoalerttheuserwhenabroadcasteventoccurs.Morecommonly,though,abroadcastreceiverisjustagatewaytoothercomponentsa
19、ndisintendedtodoaveryminimalamountofwork.Forinstance,itmightinitiateaservicetoperformsomeworkbasedontheevent.AbroadcastreceiverisimplementedasasubclassofBroadcastReceiverandeachbroadcastisdeliveredasanIntentobject.Formoreinformation,seetheBroadcastReceiverclass.AuniqueaspectoftheAndroidsystemdesigni
20、sthatanyapplicationcanstartanotherapplicationscomponent.Forexample,ifyouwanttheouseptureaphotowiththedevicecamera,theresprobablyanotherapplicationthatdoesthatandyourapplicationcanuseit,insteadofdevelopinganactivitytocaptureaphotoyourself.Youdontneedtoincorporateorevenlinktothecodefromthecameraapplic
21、ation.Instead,youcansimplystarttheactivityinthecameraapplicationthatcapturesaphoto.Whencomplete,thephotoisevenreturnedtoyourapplicationsoyoucanuseit.Totheuser,itseemsasifthecameraisactuallyapartofyourapplication.Whenthesystemstartsacomponent,itstartstheprocessforthatapplication(ifitsnotalreadyrunnin
22、g)andinstantiatestheclassesneededforthecomponent.Forexample,ifyourapplicationstartstheactivityinthecameraapplicationthatcapturesaphoto,thatactivityrunsintheprocessthatbelongstothecameraapplication,notinyourapplicationsprocess.Therefore,unlikeapplicationsonmostothersystems,Androidapplicationsdonthave
23、asingleentrypoint(theresnomain()function,forexample).Becausethesystemrunseachapplicationinaseparateprocesswitthatrestrictaccesstootherapplications,yourapplicationcannotdirectlyactivateacomponentfromanotherapplication.TheAndroidsystem,however,can.So,toactivateacomponentinanotherapplication,youmustdel
24、iveramessagetothesystemthatspecifiesyountenttostartaparticularcomponent.Thesystemthenactivatesthecomponentforyou.ActivatingComponentsThreeofthefourcomponenttypes-activities,services,andbroadcastreceiversareactivatedbyanasynchronousmessagecalledantent.Intentsbindindividualcomponentstoeachotheratrunti
25、me(youcanthinkofthemasthemessengersthatrequestanactionfromothercomponents),whetherthecomponentbelongstoyourapplicationoranother.AnintentiscreatedwithanIntentobject,whichdefinesamessagetoactivateeitheraspecificcomponentoraspecifictypeofcomponentanintentcanbeeitherexplicitorimplicit,respectively.Forac
26、tivitiesandservices,anintentdefinestheactiontoperform(forexample,tovieworsendsomething)andmayspecifytheURIofthedatatoacton(amongotherthingsthatthecomponentbeingstartedmightneedtoknow).Forexample,anintentmightconveyarequestforanactivitytoshowanimageortoopenawebpage.Insomecases,youcanstartanactivityto
27、receivearesult,inwhichcase,theactivityalsoreturnstheresultinanIntent(forexample,youcanissueanintenttolettheuserpickapersonalcontactandhaveitreturnedtoyouthereturnintentincludesaURIpointingtothechosencontact).Forbroadcastreceivers,theintentsimplydefinestheannouncementbeingbroadcast(forexample,abroadc
28、asttoindicatethedevicebatteryislowincludesonlyaknownactionstringthatindicatesbatteryislow).Theothercomponenttype,contentprovider,isnotactivatedbyintents.Rather,itisactivatedwhentargetedbyarequestfronaContentResolverThecontentresolverhandlesalldirecttransactionswiththecontentprovidersothatthecomponen
29、tthatsperformingtransactionswiththeproviderdoesntneedtoandinsteadcallsmethodsontheContentResolverobject.Thisleavesalayerofabstractionbetweenthecontentproviderandthecomponentrequestinginformation(forsecurity).Thereareseparatemethodsforactivatingeachtypeofcomponent:?Youcanstartanactivity(orgiveitsomet
30、hingnewtodo)bypassinganIntenttostartActivity()orstartActivityForResult()(whenyouwanttheactivitytoreturnaresult).?Youcanstartaservice(orgivenewinstructionstoanongoingservice)bypassinganIntenttostartService().OryoucanbindtotheservicebypassinganIntenttobindService().?Youcaninitiateabroadcastbypassingal
31、ntenttomethodslikesendBroadcast()sendOrderedBroadcast,)orsendStickyBroadcast()?Youcanperformaquerytoacontentproviderbycallingquery()onaContentResolverFormoreinformationaboutusingintents,seethententsandIntentFiltersdocument.Moreinformationaboutactivatingspecificcomponentsisalsoprovidedinthefollowingd
32、ocuments:Activities,ServicesBroadcastReceiverandContentProvidersDeclaringcomponentsTheprimarytaskofthemanifestistoinformthesystemabouttheapplicationscomponents.Forexample,amanifestdeclareanactivityasfollows:/activity.Intheelement,theandroid:iconattributepointstoresourcesforaniconthatidentifiestheapp
33、lication.Intheelement,theandroid:nameattributespecifiesthefUlyqualifiedclassnameoftheActivitysubclassandtheandroid:labelattributesspecifiesastringtouseastheuser-visiblelabelfortheactivity.Youmustdeclareallapplicationcomponentsthisway:elementsforactivitieselementsforserviceselementsforbroadcastreceiv
34、erselementsforcontentprovidersActivities,services,andcontentprovidersthatyouincludeinyoursourcebutdonotdeclareinthemanifestarenotvisibletothesystemand,consequently,canneverrun.However,broadcastreceiverscanbeeitherdeclaredinthemanifestorcreateddynamicallyincode(asBroadcastReceiverobjects)andregistere
35、dwiththesystembycallingregisterReceiver()DeclaringcomponentcapabilitiesAsdiscussedabove,inActivatingComponents,youcanuseanIntenttostartactivities,services,andbroadcastreceivers.Youcandosobyexplicitlynamingthetargetcomponent(usingthecomponentclassname)intheintent.However,therealpowerofintentsliesinth
36、econceptofintentactions.Withintentactions,yousimplydescribethetypeofactionyouwanttoperform(andoptionally,thedatauponwhichyoudliketoperformtheaction)andallcthesystemtofindacomponentonthedevicethatcanperformtheactionandstartit.Iftherearemultiplecomponentsthatcanperformtheactiondescribedbytheintent,the
37、ntheuserselectswhichonetouse.Thewaythesystemidentifiesthecomponentsthatcanrespondtoanintentisbycomparingtheintentreceivedtotheintentfiltersprovidedinthemanifestotherapplicationsonthedevice.Whenyoudeclareacomponentinyourapplicationsmanifest,youcanoptionallyincludeintentfiltersthatdeclarethecapabiliti
38、esofthecomponentsoitcanrespondtointentsfromotherapplications.Youcandeclareanintentilterforyourcomponentbyaddinganelementasachildofthecomponentsdeclarationelement.Forexample,anemailapplicationwithanactivityforcomposinganewemailmightdeclareanintentfilterinitsmanifestentrytorespondtosendintents(inorder
39、tosendemail).Anactivityinyourapplicationcanthencreateanintentwiththe”sene(ACTION_SEND),whichthesystemmatchestotheemailapplicationssend”actilaunchesitwhenyouinvoketheintentwithstartActivity().Formoreaboutcreatingintentfilters,seethententsandIntentFiltersdocument.DeclaringapplicationrequirementsTherea
40、reavarietyofdevicespoweredbyAndroidandnotallofthemprovidethesamefeaturesandcapabilities.Inordertopreventyourapplicationfrombeinginstalledondevicesthatlackfeaturesneededbyyourapplication,itsimportantthatyouclearlydefineaprothetypesofdevicesyourapplicationsupportsbydeclaringdeviceandsoftwarerequiremen
41、tsinyourmanifestfile.Mostofthesedeclarationsareinformationalonlyandthesystemdoesnotreadthem,butexternalservicessuchasGooglePlaydoreadtheminordertoprovidefilteringforuserswhentheysearchforapplicationsfromtheirdevice.Forexample,ifyourapplicationrequiresacameraandusesAPIsintroducedinAndroid2.1(APILevel
42、7),youshoulddeclaretheseasrequirementsinyourmanifestfile.Thatway,devicesthatdonothaveacameraandhaveanAndroidversionowerthan2.1cannotinstallyourapplicationfromGooglePlay.However,youcanalsodeclarethatyourapplicationusesthecamera,butdoesnotrequireit.Inthatcase,yourapplicationmustperformacheckatruntimet
43、odetermineifthedevicehasacameraanddisableanyfeaturesthatusethecameraifoneisnotavailable.Herearesomeoftheimportantdevicecharacteristicsthatyoushouldconsiderasyoudesignanddevelopyourapplication:ScreensizeanddensityInordertocategorizedevicesbytheirscreentype,Androiddefinestwocharacteristicsforeachdevic
44、e:screensize(thephysicaldimensionsofthescreen)andscreendensity(thephysicaldensityofthepixelsonthescreen,ordpi-dotsperinch).Tosimplifyallthedifferenttypesofscreenconfigurations,theAndroidsystemgeneralizesthemintoselectgroupsthatmakethemeasiertotarget.Thescreensizesare:small,normal,large,andextralarge
45、.Thescreendensitiesare:lowdensity,mediumdensity,highdensity,andextrahighdensity.Bydefault,yourapplicationiscompatiblewithallscreensizesanddensities,becausetheAndroidsystemmakestheappropriateadjustmentstoyourUIlayoutandimageresources.However,youshouldcreatespecializedlayoutsforcertainscreensizesandpr
46、ovidespecializedimagesforcertaindensities,usingalternativelayoutresources,andbydeclaringinyourmanifestexactlywhichscreensizesyourapplicationsupportswiththeelement.Formoreinformation,seetheSupportingMultipleScreensdocument.InputconfigurationsManydevicesprovideadifferenttypeofuserinputmechanism,suchas
47、ahardwarekeyboard,atrackball,orafive-waynavigationpad.Ifyourapplicationrequiresaparticularkindofinputhardware,thenyoushoulddeclareitinyourmanifestwiththeelement.However,itisrarethatanapplicationshouldrequireacertaininputconfiguration.DevicefeaturesTherearemanyhardwareandsoftwarefeaturesthatmayormayn
48、otexistonagivenAndroid-powereddevice,suchasacamera,alightsensor,bluetooth,acertainversionofOpenGL,orthefidelityofthetouchscreen.YoushouldneverassumethatacertainfeatureisavailableonallAndroid-powereddevices(otherthantheavailabilityofthestandardAndroidlibrary),soyoushoulddeclareanyfeaturesusedbyyourap
49、plicationwiththeelement.PlatformVersionDifferentAndroid-powereddevicesoftenrundifferentversionsoftheAndroidplatform,suchasAndroid1.6orAndroid2.3.EachsuccessiveversionoftenincludesadditionalAPIsnotavailableinthepreviousversion.InordertoindicatewhichsetofAPIsareavailable,eachplatformversionspecifiesan
50、APILevel(forexample,Android1.0isAPILevel1andAndroid2.3isAPILevel9).IfyouuseanyAPIsthatwereaddedtotheplatformafterversion1.0,youshoulddeclaretheminimumAPILevelinwhichthoseAPIswereintroducedusingtheelement.Itsimportantthatyoudeclareallsuchrequirementsforyourapplication,because,whenyoudistributeyourapp
51、licationonGooglePlay,thestoreusesthesedeclarationstofilterwhichapplicationsareavailableoneachdevice.Assuch,yourapplicationshouldbeavailableonlytodevicesthatmeetallyourapplicationrequirements.FormoreinformationabouthowGooglePlayfiltersapplicationsbasedonthese(andother)requirements,seethiltersonGoogle
52、Playdocument.ApplicationResourcesAnAndroidapplicationiscomposedofmorethanjustcode-itrequiresresourcesthatareseparatefromthesourcecode,suchasimages,audiofiles,andanythingrelatingtothevisualpresentationoftheapplication.Forexample,youshoulddefineanimations,menus,styles,colors,andthelayoutofactivityuser
53、interfaceswithXMLfiles.Usingapplicationresourcesmakesiteasytoupdatevariouscharacteristicsofyourapplicationwithoutmodifyingcodeandbyprovidingsetsofalternativeresources-enablesyoutooptimizeyourapplicationforavarietyofdeviceconfigurations(suchasdifferentlanguagesandscreensizes).Foreveryresourcethatyoui
54、ncludeinyourAndroidproject,theSDKbuildtoolsdefineauniqueintegerID,whichyoucanusetoreferencetheresourcefromyourapplicationcodeorfromotherresourcesdefinedinXML.Forexample,ifyourapplicationcontainsanimagelogo.png(savedintheres/drawable/directory),theSDKtoolsgeneratearesourceIDnamedR.drawable.logQwhichy
55、oucanusetoreferencetheimageandinsertitinyouruserinterface.Oneofthemostimportantaspectsofprovidingresourcesseparatefromyoursourcecodeistheabilityforyoutoprovidealternativeresourcesfordifferentdeviceconfigurations.Forexample,bydefiningUIstringsinXML,youcantranslatethestringsintootherlanguagesandsaveth
56、osestringsinseparatefiles.Then,basedonalanguagealifierthatyouappendtotheresourcedirectorysname(suchares/values-fr/forFrenchstringvalues)andtheuserslanguagesetting,theAndroidsystemappliestheappropriatelanguagestringstoyourUI.Androidsupportsmanydifferentqualifiersforyouralternativeresources.Thequalifi
57、erisashortstringthatyouincludeinthenameofyourresourcedirectoriesinordertodefinethedeviceconfigurationforwhichthoseresourcesshouldbeused.Asanotherexample,youshouldoftencreatedifferentlayoutsforyouractivities,dependingonthedevicesscreenorientationandsize.Forexample,whenthedevicescreenisinportraitorientation(tall),youmightwantalayoutwithbuttonstobevertical,butwhenthescreenisinlandscapeorientation(wide),thebuttonsshouldbealignedhorizontally.Tochangethelayoutdependingontheorientation,youcandefinetwodifferentlayoutsandapplytheappropriatequalifiertoeachlayoutsdirectoryname.Then,thesy
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年北京邮电大学集成电路学院招聘真题
- 借款合同的专业指导
- 创业扶持与公共服务的协同试题及答案
- 2025年乐理旋律理解试题及答案
- 2025年化学工程与技术的结合探讨试题及答案
- 2025年大学物理逆向思维试题及答案
- 盾构机施工中的隧道工程地质模型验证考核试卷
- 智能健身工作室连锁会员服务体验优化报告
- 海洋地质调查在油气开采中的作用考核试卷
- 生态脆弱区域治理考核试卷
- 海绵城市项目专项工程施工方案
- 同仁堂集团招聘笔试题库2024
- 2023年二级注册计量师考试题目及答案
- 化工1.4丁二醇介绍及生产流程设计书
- 急性冠脉综合征
- 公路水运工程施工企业主要负责人和安全生产管理人员考核大纲和模拟试题库1
- 办公耗材采购服务方案(技术方案)
- 泵、真空设备企业数字化转型策略
- 北师大版小学心理健康教材目录
- 幽门螺杆菌科普课件
- 国开(河北)2024年《社会学概论》形考作业1-4答案
评论
0/150
提交评论