Thông tin tài liệu
9/12/2011
1
Part3
Android
Application’sLifeCycle
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
Ul ki Ad id
U
n
l
oc
ki
ng
A
n
d
ro
id
byFrankAbleson,CharlieCollins,andRobi Sen.
ISBN978‐1‐933988‐67‐2
ManningPublications,2009.
AndroidDevelopers
http://developer.android.com/index.html
3.Android– Application'sLifeCycle
AndroidApplications
Anapplicationconsistsofoneormorecomponents thatare
defined in the application
'
s manifest file. A component can be one
defined
in
the
application s
manifest
file.
A
component
can
be
one
ofthefollowing:
1. AnActivity
2. AService
3. Abroadcastreceiver
4.
A
contentprovide
r
22
9/12/2011
2
3.Android– Application'sLifeCycle
AndroidApplications
1.Activity
Anactivity usuallypresentsasinglevisualuserinterfacefromwhichanumberof
actionscouldbeperformed.
Altoughactivitiesworktogethertoformacohesiveuserinterface,eachactivity
isindependentoftheothers.
Typically,oneoftheactivitiesismarkedasthefirst onethatshouldbepresented
3
totheuserwhentheapplicationislaunched.
Movingfromoneactivitytoanotherisaccomplishedbyhavingthecurrent
activitystartthenextonethroughsocalledintents.
3
Reference:FriedgerMüffke(friedger@openintents.org)
3.Android– Application'sLifeCycle
AndroidApplications
2.Service
Aservicedoesn'thaveavisualuserinterface,butratherrunsinthebackground
foranindefiniteperiodoftime.
It'spossibletoconnectto(bindto)anongoingservice(andstarttheserviceifit's
notalreadyrunning).
4
Whileconnected,youcancommunicatewiththeservicethroughaninterface
thattheserviceexposes.
4
Reference:FriedgerMüffke(friedger@openintents.org)
9/12/2011
3
3.Android– Application'sLifeCycle
AndroidApplications
3.Broadcastreceiver
Abroadcastreceiver isacomponentthatdoesnothingbutreceiveandreactto
broadcastannouncements.
Manybroadcastsoriginateinsystemcode(eg.“yougotmail“)butanyother
applicationscanalsoinitiatebroadcasts.
Broadcastreceiversdonotdis
p
la
y
auserinter
f
ace.However
,
the
y
ma
y
startan
5
py f
, y y
activityinresponsetotheinformationtheyreceive,or‐ asservicesdo‐ they
mayusethenotificationmanagertoalerttheuser.
5
Reference:FriedgerMüffke(friedger@openintents.org)
3.Android– Application'sLifeCycle
AndroidApplications
4.Contentprovider
Acontentprovider makesaspecificsetoftheapplication'sdataavailableto
otherapplications.
Thedatausuallyisstoredinthefilesystem,orinanSQLitedatabase.
Thecontentproviderimplementsastandardsetofmethodsthatenableother
applicationstoretrieveandstoredataofthetypeit
controls.
6
However,applicationsdonotcallthesemethodsdirectly.Rathertheyusea
contentresolverobjectandcallitsmethodsinstead.Acontentresolvercantalk
toanycontentprovider;itcooperateswiththeprovidertomanageany
interprocesscommunicationthat'sinvolved.
6
Reference:FriedgerMüffke(friedger@openintents.org)
9/12/2011
4
3.Android– Application'sLifeCycle
AndroidApplications
EveryAndroidapplicationrunsinitsownprocess
(
with its own instance of the Dalvik virtual machine
).
(
with
its
own
instance
of
the
Dalvik
virtual
machine
).
Wheneverthere'sarequestthatshouldbehandledbyaparticularcomponent,
• Androidmakessurethattheapplicationprocessofthecomponentis
running,
• startingitifnecessary,and
• thatanappropriateinstanceofthecomponentisavailable,creatingthe
instanceifnecessary.
77
3.Android– Application'sLifeCycle
Application’sLifeCycle
ALinux
p
rocessenca
p
sulatin
g
anAndroida
pp
licationiscreatedforthe
p pg pp
applicationwhensomeofitscodeneedstoberun,andwillremain
runninguntil
1. itisnolongerneeded,OR
2. thesystemneedstoreclaimitsmemoryforusebyother
applications.
88
9/12/2011
5
3.Android– Application'sLifeCycle
Application’sLifeCycle
AnunusualandfundamentalfeatureofAndroidisthat ana
pp
lication
pp
process'slifetimeis not directlycontrolledbytheapplicationitself.
Instead,itisdeterminedbythesystemthroughacombinationof
1. thepartsoftheapplicationthatthesystemknowsarerunning,
2. howimportantthesethingsaretotheuser,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'sLifeCycle
ComponentLifecycles
Applicationcomponentshavea lifecycle
1. Abeginning whenAndroidinstantiatesthemtorespondto
intents
2. Anend whentheinstancesaredestroyed.
3. Inbetween,theymaysometimesbeactive orinactive,or‐inthe
caseofactivities‐ visible totheuserorinvisible.
1010
LifeasanAndroidApplication:
Active/Inactive
Visible/Invisible
Start
End
9/12/2011
6
3.Android– Application'sLifeCycle
Activty Stack
• Activitiesinthes
y
stemaremana
g
edasanactivit
y
stack.
y g
y
• Whenanewactivityisst arted,itisplacedonthetop ofthe
stackandbecomestherunningactivity‐‐ the previous
activityalwaysremainsbelowitinthestack,andwillnot
cometotheforegroundagainuntilthenewactivityexits.
1111
• IftheuserpressestheBackButtonthenextactivityonthe
stackmovesupandbecomesactive.
3.Android– Application'sLifeCycle
ActivityStack
NewActivity RunningActivity
LastRunning
Activity
Activityn‐1
. . .
NewActivity
started
Backbuttonpushedor
runningactivityclosed
Activity Stack
1212
Activity1
Activity2
Activity3
.
.
.
Activity
Stack
Previous
Activities
Removedto
freeresources
Figure1.
9/12/2011
7
3.Android– Application'sLifeCycle
LifeCycleStates
Anactivityhasessentially
threestates:
1. Itisactive orrunning
2. Itispaused or
3. Itisstopped .
1313
Figure2.
3.Android– Application'sLifeCycle
LifeCycleStates
Anactivityhasessentiallythreestates:
1. Itisactive orrunning whenitisintheforeground ofthescreen
(atthetopoftheactivitystackforthecurrenttask).
Thisistheactivitythatisthefocusfortheuser'sactions.
141414
9/12/2011
8
3.Android– Application'sLifeCycle
LifeCycleStates
An activityhasessentiallythreestates(cont.):
2. Itispaused ifithaslostfocusbutisstillvisibletotheuser.
Thatis,anotheractivityliesontopofitandthatnewactivityeitheris
transparent ordoesn'tcoverthefullscreen.
Apausedactivityiscompletelyalive (itmaintainsallstateandmember
informationandremains
attachedtothewindowmana
g
er
),
butcanbe
151515
g),
killedbythesysteminextremelowmemorysituations.
3.Android– Application'sLifeCycle
LifeCycleStates
Anactivityhasessentiallythreestates(cont.):
3. Itisstopped ifitiscompletelyobscured byanotheractivity.
Itstillretainsallstateandmemberinformation.However,itisnolonger
visibletotheusersoitswindowishiddenanditwilloftenbekilledby
thesystemwhenmemoryisneededelsewhere.
161616
9/12/2011
9
3.Android– Application'sLifeCycle
Application’s
LifeCycle
1717
Figure3.
3.Android– Application'sLifeCycle
Application’sLifeCycle
Yourturn!
EXPERIMENT1.
Teachingnotes
1. W r iteanAndroidapp.(“PuraVida”)toshowthedifferentcyclesfollowedbyan
application.
2. Themain.xmllayoutshouldincludeaButton(text:“Finish”,id:btnFinish)and
anEditTe xt container(txt:“”andidtxtMsg).
3. UsetheonCreate methodtoconnectthebuttonandtextboxtotheprogram.
Addthefollowinglineofcode:
Toast.makeText(this, "onCreate", 1).show();
4. Theclickmethodhasonlyonecommand:finish(); calledtoterminatethe
1818
application.AddaToast‐command(astheoneabove)toeachofthe remaining
sixmainevents.Tosimplifyyourjob usetheEclipse’stopmenu:Source>
Override/ImplementMethods…
5. Ontheoptionwindowcheckmarkeachofthefollowingevents:onStart,
onResume,onPause,onStop,onDestry,onRestart
(noticehowmanyonEvent… methods
arethere!!!)
6. Saveyourcode.
9/12/2011
10
3.Android– Application'sLifeCycle
Application’sLifeCycle
Yourturn!
EXPERIMENT1(cont.)
Teachingnotes
7. Compileandexecuteapplication.
8. W r itedownthesequenceofmessagesdisplayedbytheToast‐commands.
9. PresstheFINISHbutton.Observethesequenceofstates.
10. Re‐executetheapplication
11. Pressemulator’sHOMEbutton.Whathappens?
12. Clickonlaunchpad,lookforiconandreturntothe“PuraVida”app.What
sequenceofmessagesisdisplayed?
13. Click
ontheemulator’sCALL
(
Green
p
hone
)
.Isthea
pp
p
ausedorsto
pp
ed?
1919
( p) pp p pp
14. ClickontheBACKbuttontoreturntotheapplication.
15. Long‐tapontheemulator’sHANG‐UPbutton.Whathappens?
3.Android– Application'sLifeCycle
Application’sLifeCycle
Yourturn!
EXPERIMENT2
Teachingnotes
7. Runasecondemulator.
1. Makeavoice‐calltothefirstemulatorthatisstillshowingourapp.What
happensonthiscase?(real‐timesynchronousrequest)
2. Sendatext‐messagetofirstemulator(asynchronousattentionrequest)
8. W r iteaphraseintheEditText box(“thesearethebestmomentsofmylife….”).
9. Re‐ex ecutethea
pp
.Whatha
pp
enedtothetext?
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
Xem thêm: Android chapter03 life cycle