1. Trang chủ
  2. » Công Nghệ Thông Tin

Android chapter03 life cycle

26 310 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 26
Dung lượng 556,41 KB

Nội dung

9/12/2011 1 Part3 Android Application’sLifeCycle VictorMatos ClevelandStateUniversity Notesarebasedon: Ul ki Ad id U n l oc ki ng A n d ro id  byFrankAbleson,CharlieCollins,andRobi Sen. ISBN978‐1‐933988‐67‐2 ManningPublications,2009. AndroidDevelopers http://developer.android.com/index.html 3.Android– Application'sLifeCycle AndroidApplications Anapplicationconsistsofoneormorecomponents thatare defined in the application ' s manifest file. A component can be one defined  in  the  application s  manifest  file.  A  component  can  be  one  ofthefollowing: 1. AnActivity 2. AService 3. Abroadcastreceiver 4. A contentprovide r 22 9/12/2011 2 3.Android– Application'sLifeCycle AndroidApplications 1.Activity Anactivity usuallypresentsasinglevisualuserinterfacefromwhichanumberof actionscouldbeperformed. Altoughactivitiesworktogethertoformacohesiveuserinterface,eachactivity isindependentoftheothers. Typically,oneoftheactivitiesismarkedasthefirst onethatshouldbepresented 3 totheuserwhentheapplicationislaunched. Movingfromoneactivitytoanotherisaccomplishedbyhavingthecurrent activitystartthenextonethroughsocalledintents. 3 Reference:FriedgerMüffke(friedger@openintents.org) 3.Android– Application'sLifeCycle AndroidApplications 2.Service Aservicedoesn'thaveavisualuserinterface,butratherrunsinthebackground foranindefiniteperiodoftime. It'spossibletoconnectto(bindto)anongoingservice(andstarttheserviceifit's notalreadyrunning). 4 Whileconnected,youcancommunicatewiththeservicethroughaninterface thattheserviceexposes. 4 Reference:FriedgerMüffke(friedger@openintents.org) 9/12/2011 3 3.Android– Application'sLifeCycle AndroidApplications 3.Broadcastreceiver Abroadcastreceiver isacomponentthatdoesnothingbutreceiveandreactto broadcastannouncements. Manybroadcastsoriginateinsystemcode(eg.“yougotmail“)butanyother applicationscanalsoinitiatebroadcasts. Broadcastreceiversdonotdis p la y auserinter f ace.However , the y ma y startan 5 py f , y y activityinresponsetotheinformationtheyreceive,or‐ asservicesdo‐ they mayusethenotificationmanagertoalerttheuser. 5 Reference:FriedgerMüffke(friedger@openintents.org) 3.Android– Application'sLifeCycle AndroidApplications 4.Contentprovider Acontentprovider makesaspecificsetoftheapplication'sdataavailableto otherapplications. Thedatausuallyisstoredinthefilesystem,orinanSQLitedatabase. Thecontentproviderimplementsastandardsetofmethodsthatenableother applicationstoretrieveandstoredataofthetypeit controls. 6 However,applicationsdonotcallthesemethodsdirectly.Rathertheyusea contentresolverobjectandcallitsmethodsinstead.Acontentresolvercantalk toanycontentprovider;itcooperateswiththeprovidertomanageany interprocesscommunicationthat'sinvolved. 6 Reference:FriedgerMüffke(friedger@openintents.org) 9/12/2011 4 3.Android– Application'sLifeCycle AndroidApplications EveryAndroidapplicationrunsinitsownprocess ( with its own instance of the Dalvik virtual machine ). ( with  its  own  instance  of  the  Dalvik  virtual  machine ).  Wheneverthere'sarequestthatshouldbehandledbyaparticularcomponent, • Androidmakessurethattheapplicationprocessofthecomponentis running, • startingitifnecessary,and • thatanappropriateinstanceofthecomponentisavailable,creatingthe instanceifnecessary. 77 3.Android– Application'sLifeCycle Application’sLifeCycle ALinux p rocessenca p sulatin g anAndroida pp licationiscreatedforthe p pg pp applicationwhensomeofitscodeneedstoberun,andwillremain runninguntil 1. itisnolongerneeded,OR 2. thesystemneedstoreclaimitsmemoryforusebyother applications. 88 9/12/2011 5 3.Android– Application'sLifeCycle Application’sLifeCycle AnunusualandfundamentalfeatureofAndroidisthat ana pp lication pp process'slifetimeis not directlycontrolledbytheapplicationitself. Instead,itisdeterminedbythesystemthroughacombinationof 1. thepartsoftheapplicationthatthesystemknowsarerunning, 2. howimportantthesethingsaretotheuser,and 3. how much overall memory is available in the sys tem. 9 3. how  much  overall  memory  is  available  in  the  system. 9 3.Android– Application'sLifeCycle ComponentLifecycles Applicationcomponentshavea lifecycle 1. Abeginning whenAndroidinstantiatesthemtorespondto intents 2. Anend whentheinstancesaredestroyed. 3. Inbetween,theymaysometimesbeactive orinactive,or‐inthe caseofactivities‐ visible totheuserorinvisible. 1010 LifeasanAndroidApplication: Active/Inactive Visible/Invisible Start End 9/12/2011 6 3.Android– Application'sLifeCycle Activty Stack • Activitiesinthes y stemaremana g edasanactivit y stack. y g y • Whenanewactivityisst arted,itisplacedonthetop ofthe stackandbecomestherunningactivity‐‐ the previous activityalwaysremainsbelowitinthestack,andwillnot cometotheforegroundagainuntilthenewactivityexits. 1111 • IftheuserpressestheBackButtonthenextactivityonthe stackmovesupandbecomesactive. 3.Android– Application'sLifeCycle ActivityStack NewActivity RunningActivity LastRunning Activity Activityn‐1 . . . NewActivity started Backbuttonpushedor runningactivityclosed Activity Stack 1212 Activity1 Activity2 Activity3 .  .  . Activity  Stack Previous Activities Removedto freeresources Figure1. 9/12/2011 7 3.Android– Application'sLifeCycle LifeCycleStates Anactivityhasessentially threestates: 1. Itisactive orrunning 2. Itispaused or 3. Itisstopped . 1313 Figure2. 3.Android– Application'sLifeCycle LifeCycleStates Anactivityhasessentiallythreestates: 1. Itisactive orrunning whenitisintheforeground ofthescreen (atthetopoftheactivitystackforthecurrenttask). Thisistheactivitythatisthefocusfortheuser'sactions. 141414 9/12/2011 8 3.Android– Application'sLifeCycle LifeCycleStates An activityhasessentiallythreestates(cont.): 2. Itispaused ifithaslostfocusbutisstillvisibletotheuser. Thatis,anotheractivityliesontopofitandthatnewactivityeitheris transparent ordoesn'tcoverthefullscreen. Apausedactivityiscompletelyalive (itmaintainsallstateandmember informationandremains attachedtothewindowmana g er ), butcanbe 151515 g), killedbythesysteminextremelowmemorysituations. 3.Android– Application'sLifeCycle LifeCycleStates Anactivityhasessentiallythreestates(cont.): 3. Itisstopped ifitiscompletelyobscured byanotheractivity. Itstillretainsallstateandmemberinformation.However,itisnolonger visibletotheusersoitswindowishiddenanditwilloftenbekilledby thesystemwhenmemoryisneededelsewhere. 161616 9/12/2011 9 3.Android– Application'sLifeCycle Application’s LifeCycle 1717 Figure3. 3.Android– Application'sLifeCycle Application’sLifeCycle Yourturn! EXPERIMENT1. Teachingnotes 1. W r iteanAndroidapp.(“PuraVida”)toshowthedifferentcyclesfollowedbyan application. 2. Themain.xmllayoutshouldincludeaButton(text:“Finish”,id:btnFinish)and anEditTe xt container(txt:“”andidtxtMsg). 3. UsetheonCreate methodtoconnectthebuttonandtextboxtotheprogram. Addthefollowinglineofcode: Toast.makeText(this, "onCreate", 1).show(); 4. Theclickmethodhasonlyonecommand:finish(); calledtoterminatethe 1818 application.AddaToast‐command(astheoneabove)toeachofthe remaining sixmainevents.Tosimplifyyourjob usetheEclipse’stopmenu:Source> Override/ImplementMethods… 5. Ontheoptionwindowcheckmarkeachofthefollowingevents:onStart, onResume,onPause,onStop,onDestry,onRestart (noticehowmanyonEvent… methods arethere!!!) 6. Saveyourcode. 9/12/2011 10 3.Android– Application'sLifeCycle Application’sLifeCycle Yourturn! EXPERIMENT1(cont.) Teachingnotes 7. Compileandexecuteapplication. 8. W r itedownthesequenceofmessagesdisplayedbytheToast‐commands. 9. PresstheFINISHbutton.Observethesequenceofstates. 10. Re‐executetheapplication 11. Pressemulator’sHOMEbutton.Whathappens? 12. Clickonlaunchpad,lookforiconandreturntothe“PuraVida”app.What sequenceofmessagesisdisplayed? 13. Click ontheemulator’sCALL ( Green p hone ) .Isthea pp  p ausedorsto pp ed? 1919 ( p) pp p pp 14. ClickontheBACKbuttontoreturntotheapplication. 15. Long‐tapontheemulator’sHANG‐UPbutton.Whathappens? 3.Android– Application'sLifeCycle Application’sLifeCycle Yourturn! EXPERIMENT2 Teachingnotes 7. Runasecondemulator. 1. Makeavoice‐calltothefirstemulatorthatisstillshowingourapp.What happensonthiscase?(real‐timesynchronousrequest) 2. Sendatext‐messagetofirstemulator(asynchronousattentionrequest) 8. W r iteaphraseintheEditText box(“thesearethebestmomentsofmylife….”). 9. Re‐ex ecutethea pp .Whatha pp enedtothetext? 2020 pp pp [...]... LAYOUT 3. Android – Application's Life Cycle Example Life Cycle Example The following application  demonstrates some of  the state transitioning  situations experienced in  the life cycle of a typical  Android activity   /T Vi 35 3. Android – Application's Life Cycle Example: Life Cycle Code: Life Cycle Demo. Part 1... 45 3. Android – Application's Life Cycle Example: Life Cycle Code: Life Cycle Demo. Part  10 @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Toast.makeText(getBaseContext(), "onSaveInstanceState BUNDLING", Toast.LENGTH_LONG).show(); } // onSaveInstanceState }//LyfeCicleDemo 46 23 9/12/2011 3. Android – Application's Life Cycle Example: Life Cycle. .. 3. Android – Application's Life Cycle Example: Life Cycle onCreate… onStart… onResume… 47 3. Android – Application's Life Cycle onPause… Example: Life Cycle onStop… After pressing “Back Arrow” onDestroy… 48 24 9/12/2011 3. Android – Application's Life Cycle Example: Life Cycle After  pressing “Home” After  re‐executing AndLife2 After   “Back Arrow” or  Finish onSavedInstanceState >  onPause >  onStop > onRestart... android: layout_width="fill_parent" android: layout_height="fill_parent" android: background="#ff000000"  >

Ngày đăng: 16/03/2014, 23:34

TỪ KHÓA LIÊN QUAN