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
/>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()
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()
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()
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()
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
9/12/2011
11
3.Android– Application'sLifeCycle
Application’sLifeCycle
Yourturn!
EXPERIMENT3
Teachingnotes
Providedatapersistency.
18. UsetheonPause methodtoaddthefollowingfragment
SharedPreferences myFile1 = getSharedPreferences("myFile1",
Activity.MODE_PRIVATE);
SharedPreferences.Editor myEditor = myFile1.edit();
String temp = txtMsg.getText().toString();
myEditor.putString("mydata", temp);
myEditor.commit();
18
Use the
onResume
method to add the following
frament
2121
18
.
Use
the
onResume
method
to
add
the
following
frament
SharedPreferences myFile = getSharedPreferences("myFile1",
Activity.MODE_PRIVATE);
if ( (myFile != null) && (myFile.contains("mydata")) ) {
String temp = myFile.getString("mydata", "***");
txtMsg.setText(temp);
}
19. Whathappensnowwiththedatapreviouslyenteredinthetextbox?
3.Android– Application'sLifeCycle
LifeCycleEvents
Summary:APPMILESTONES
Ifanactivityispausedorstopped,thesystemcandropitfrommemoryeitherby
askingittofinish(callingitsfinish() method),orsimplykillingitsprocess.
Whenitisdisplayedagaintotheuser,itmustbecompletelyrestartedandrestored
toitspreviousstate.
Asanactivitytransitionsfromstatetostate,itisnotifiedofthechangebycallsto
thefollowingprotectedtransition methods:
2222
voidonCreate(BundlesavedInstanceState)
voidonStart()
voidonRestart()
voidonResume()
voidonPause()
voidonStop()
voidonDestroy()
9/12/2011
12
3.Android– Application'sLifeCycle
LifeCycleEvents
Allofthesemethodsarehooks thatyoucanoverridetodoappropriate
workwhenthestatechanges.
(MUST)
AllactivitiesmustimplementonCreate() todotheinitialsetup
whentheobjectisfirstinstantiated.
(HighlyRecommended)
Many activities will also implement
onPause
()
to commit data
2323
Many
activities
will
also
implement
onPause
()
to
commit
data
changesandotherwisepreparetostopinteractingwiththeuser.
3.Android– Application'sLifeCycle
Application’sLifetime
En
t
ir
e
Lif
et
im
e
te et e
Theseventransitionmethods(Figure3)definetheentirelifecycleofan
activity.
• Theentirelifetime ofanactivityhappensbetweenthefirstcallto
onCreate() throughtoasinglefinalcalltoonDestroy().
• Anactivitydoesallitsinitialsetupof"global"stateinonCreate(),
2424
andreleasesallremainingresourcesinonDestroy().
9/12/2011
13
3.Android– Application'sLifeCycle
VisibleLifetime
Vi
s
i
b
l
e
Lif
et
im
e
sbe et e
Thevisiblelifetime ofanactivityhappensbetweenacalltoonStart() untila
correspondingcalltoonStop().
Duringthistime,theusercanseetheactivityon‐screen,thoughit
maynotbeintheforegroundandinteractingwiththeuser.
• TheonStart()andonStop()methodscanbecalled
multipletimes,
2525
astheactivityalternatesbetweenbeingvisibleandhiddentothe
user.
• Betweenthesetwomethods,youcanmaintainresourcesthatare
neededtoshowtheactivitytotheuser.
3.Android– Application'sLifeCycle
ForegroundLifetime
F
o
r
eg
r
ou
n
d
Lif
et
im
e
oegou d et e
Theforegroundlifetime ofanactivityhappensbetweenacallto
onResume() untilacorrespondingcallto onPause().
Duringthistime,theactivityisinfrontofallotheractivitiesonscreen
andisinteractingwiththeuser.
Anactivitycanfrequentlytransitionbetweentheresumed andpaused
2626
states—forexample,
• onPause()iscalledwhenthedevicegoestosleeporwhenanew
activityisstarted,
• onResume()iscalledwhenanactivityresultoranewintentis
delivered.
9/12/2011
14
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onCreate()
• Calledwhentheactivityisfirstcreated.
• Thisiswhereyoushoulddoallofyournormalstaticsetup—
createviews,binddatatolists,andsoon.
• ThismethodispassedaBundle objectcontainingtheactivity's
previousstate,ifthatstatewascaptured.
• Alwa
y
sfollowedb
y
onStar
t
()
2727
y y
()
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onRestart()
• Calledaftertheactivityhasbeenstopped,justpriortoitbeing
startedagain.
• AlwaysfollowedbyonStart()
Method: onStart()
2828
• Calledjustbeforetheactivitybecomesvisibletotheuser.
• FollowedbyonResume()iftheactivitycomestotheforeground,
oronStop()ifitbecomeshidden.
9/12/2011
15
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onResume()
1. Calledjustbeforetheactivitystartsinteractingwiththeuser.
2. Atthispointtheactivityisatthetopoftheactivitystack,with
userinputgoingtoit.
3. AlwaysfollowedbyonPause().
2929
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onPause()
1. Calledwhenthesystemisabouttostartresuminganother
activity.
2. Thismethodistypicallyusedtocommit unsavedchangesto
persistentdata,stopanimationsandotherthingsthatmaybe
consumingCPU,andsoon.
3. Itshoulddowhateveritdoesver
y
q
uickl
y,
becausethenext
3030
y qy,
activitywillnotberesumeduntilitreturns.
4. FollowedeitherbyonResume()iftheactivityreturnsbacktothe
front,orbyonStop()ifitbecomesinvisibletotheuser.
5. Theactivityinthisstateiskillable bythesystem.
9/12/2011
16
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onStop()
1. Calledwhentheactivityisnolongervisibletotheuser.
2. Thismayhappenbecauseitisbeingdestroyed,orbecause
anotheractivity(eitheranexistingoneoranewone)hasbeen
resumedandiscoveringit.
3. FollowedeitherbyonRestart()iftheactivityiscomingbackto
interact
withtheuser
,
orb
y
onDestro
y
()
ifthisactivit
y
is
g
oin
g
3131
, y
y
() y gg
away.
4. Theactivityinthisstateiskillable bythesystem.
3.Android– Application'sLifeCycle
LifeCycleMethods
Method: onDestroy()
1. Calledbeforetheactivityisdestroyed.
2. Thisisthefinalcallthattheactivitywillreceive.
3. Itcouldbecalledeitherbecausetheactivityisfinishing(someone
calledfinish() onit),orbecausethesystemistemporarily
destroyingthisinstanceoftheactivitytosavespace.
4. Youcandistin
g
uishbetweenthesetwoscenarioswiththe
3232
g
isFinishing()method.
5. Theactivityinthisstateiskillable bythesystem.
9/12/2011
17
3.Android– Application'sLifeCycle
LifeCycleMethods
KillableStates
• Activitiesonkillablestatescanbeterminatedbythesystematany
timeafterthemethodreturns,withoutexecutinganotherlineofthe
activity'scode.
• Threemethods(onPause(),onStop(),andonDestroy())arekillable.
() h l h d b ll d bf h
3333
• onPause
()
ist
h
eon
l
yonet
h
atisguarantee
d
to
b
eca
ll
e
d
b
e
f
oret
h
e
processiskilled— onStop()andonDestroy()maynotbe.
• Therefore,youshoulduseonPause()towriteanypersistentdata
(suchasuseredits)tostorage.
Asanaside…
AndroidPreferences
3.Android– Application'sLifeCycle
LifeCycleMethods
Preferencesisalightweightmechanismtostoreandretrievekey‐value pairsof
primitivedatatypes.Itistypicallyusedtostoreapplicationpreferences,such
asadefaultgreetingoratextfonttobeloadedwhenevertheapplicationis
started.
CallContext.getSharedPreferences() toreadandwritevalues.
Assignanametoyoursetofpreferencesifyouwanttosharethemwithother
componentsinthesameapplication,oruse Activity.getPreferences()withno
nametokeepthemprivatetothecallingactivity.
Youcannotsharepreferencesacrossapplications(exceptbyusingacontent
provider).
3434
9/12/2011
18
3.Android– Application's LifeCycle
Example
LifeCycle
Example
LAYOUT
<?xmlversion="1.0"encoding="utf‐8"?>
<LinearLayout
xmlns:android=" />android:id="@+id/myScreen"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff000000"
>
<TextView
android:layout_width="fill_parent"
didl hih
"
"
Thefollowingapplication
demonstratessomeof
thestatetransitioning
situationsexperiencedin
thelife‐cycleofatypical
Androidactivity.
an
d
ro
id
:
l
ayout_
h
e
i
g
h
t=
"
wrap_content
"
android:text="@string/hello"
/>
<EditText
android:id="@+id/txtColorSelect"
android:hint="Backgroundcolor(red,green,blue)"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<TextView
android:id="@+id/txtToDo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00000000">
<!‐‐ transparent‐‐>
/
TVi
3535
<
/
T
ext
Vi
ew>
<Button
android:text="Finish"
android:id="@+id/btnFinish"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part1
Package cis493.lifecycle
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
//GOAL: show the following life-cycle events in action
//protected void onCreate(Bundle savedInstanceState);
// t t d id
St t
()
3636
//
pro
t
ec
t
e
d
vo
id
on
St
ar
t
()
;
//protected void onRestart();
//protected void onResume();
//protected void onPause();
//protected void onStop();
//protected void onDestroy();
9/12/2011
19
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part1
public
class
GoodLife
extends Activity {
public
class
GoodLife
extends
Activity
{
//classvariablesandconstants
publicstaticfinalStringMYPREFSID ="MyPrefs001";
publicstaticfinalint actMode =Activity.MODE_PRIVATE;
LinearLayout myScreen;
EditText txtColorSelect;
TextView txtToDo;
3737
Button btnFinish;
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState
)
;
setContentView(R.layout.main);
myScreen = (LinearLayout) findViewById(R.id.myScreen);
txtToDo = (TextView) findViewById(R.id.txtToDo);
String msg = "Instructions: \n "
+ "0. New instance (onCreate, onStart, onResume) \n "
+ "1. Back Arrow (onPause, onStop, onDestroy) \n "
+ "2. Finish (onPause, onStop, onDestroy) \n "
+ "3. Home (onPause, onStop) \n "
+ "4. After 3 > A
pp
Tab > re
-
e
xecute current a
pp
\
n
"
3838
pp
pp
+ " (onRestart, onStart, onResume) \n "
+ "5. Run DDMS > Receive a phone call or SMS \n "
+ " (onRestart, onStart, onResume) \n "
+ "6. Enter some data - repeat steps 1-5 \n ";
txtToDo.setText(msg);
9/12/2011
20
Code:LifeCycleDemo.Part2
txtColorSelect = (EditText) findViewById(R.id.txtColorSelect);
// you may want to skip discussing the listener until later
ll
dd h d i
(
tth
(){
3.Android– Application'sLifeCycle
Example:LifeCycle
txtCo
l
orSe
l
ect.a
dd
TextC
h
ange
d
L
i
stener
(
n
e
w
T
ex
t
Wa
t
c
h
er
(){
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
changeBackgroundColor(s.toString());
}
});
btnFinish = (Button) findViewById(R.id.btnFinish);
btnFinish.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
Toast.makeText(getApplicationContext(), "onCreate", 1).show();
}
3939
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part3
@Override
protected void onPause() {
super.onPause();
saveDataFromCurrentState();
Toast.makeText(this, "onPause", 1).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart", 1).show();
}
4040
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume", 1).show();
}
9/12/2011
21
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part4
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
updateFromSavedState();
Toast.makeText(this, "onStart", 1).show();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
4141
Toast.makeText(this, "
o
nDestroy
"
,
1).show();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop", 1).show();
}
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part5
protected void saveDataFromCurrentState() {
SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);
hdf di
di
fdi
()
S
h
are
d
Pre
f
erences.E
di
tor
m
yE
di
tor
=
m
yPre
f
s.e
di
t
()
;
myEditor.putString("myBkColor", txtColorSelect.getText().toString());
myEditor.commit();
}// saveDataFromCurrentState
protected void updateFromSavedState() {
SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);
if ((myPrefs != null) && (myPrefs.contains("myBkColor"))) {
String theChosenColor = myPrefs.getString("myBkColor", "");
txtColorSelect.setText
(
t
heChosenColor
)
;
4242
changeBackgroundColor(theChosenColor);
}
}// UpdateFromSavedState
protected void clearMyPreferences() {
SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);
SharedPreferences.Editor myEditor = myPrefs.edit();
myEditor.clear();
myEditor.commit();
}
9/12/2011
22
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part6
private void changeBackgroundColor (String theChosenColor){
//hbkdl
//
c
h
ange
b
ac
k
groun
d
co
l
or
if (theChosenColor.contains("red"))
myScreen.setBackgroundColor(0xffff0000);
else if (theChosenColor.contains("green"))
myScreen.setBackgroundColor(0xff00ff00);
else if (theChosenColor.contains("blue"))
myScreen.setBackgroundColor(0xff0000ff);
else {
//reseting user preferences
clearMyPreferences();
myScreen.setBackgroundColor
(
0xff000000);
4343
}
}
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part8
/*
protectedvoidonRestoreInstanceState(BundlesavedInstanceState)
ThismethodiscalledafteronStart()whentheactivityisbeingre‐initialized
fromapreviouslysavedstate.
Thedefaultimplementationofthismethodperformsarestoreofanyviewstate
thathadpreviouslybeenfrozenbyonSaveInstanceState(Bundle).
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast.makeText(getBaseContext(),
"onRestoreInstanceState
.
BUNDLING"
,
4444
,
Toast.LENGTH_LONG).show();
}
9/12/2011
23
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part9
/*
d id
(dl
)
protecte
d
vo
id
onSaveInstanceState
(
Bun
dl
eoutState
)
Calledtoretrieveper‐instancestatefromanactivitybeforebeingkilled
sothatthestatecanberestoredin
onCreate(Bundle)or
onRestoreInstanceState(Bundle)(theBundlepopulatedbythismethod
willbepassedtoboth).
Thismethodiscalledbeforeanactivitymaybekilledsothatwhenitcomes
back
sometimeinthefutureitcanrestoreitsstate.Forexample,ifactivityB
islaunchedinfrontofactivityA,andatsomepointactivityAiskilledto
reclaimresources,activit
y
Awillhaveachancetosavethecurrentstateo
f
4545
y f
itsuserinterfaceviathismethodsothatwhentheuserreturnstoactivityA,
thestateoftheuserinterfacecanberestoredvia:
onCreate(Bundle)oronRestoreInstanceState(Bundle).
*/
3.Android– Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part10
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(getBaseContext(),
"onSaveInstanceState BUNDLING",
Toast.LENGTH_LONG).show();
} // onSaveInstanceState
}//LyfeCicleDemo
4646
9/12/2011
24
3.Android– Application'sLifeCycle
Example:LifeCycle
onCreate… onStart… onResume…
4747
3.Android– Application'sLifeCycle
Example:LifeCycle
onPause… onStop… onDestroy…
4848
Afterpressing“BackArrow”
9/12/2011
25
3.Android– Application'sLifeCycle
Example:LifeCycle
After
pressing“Home”
After
re‐executingAndLife2
After
“BackArrow”orFinish
onSavedInstanceState >
onPause >
onStop >
onRestart >
onStart >
onResume >
onPause >
onStop >
onDestroy >
PreservingStateInformation
1
Enter
data:
“
Hasta
la vista!
”
4949
EndofExample
1
.
Enter
data:
Hasta
la
vista!
2. ClickHomebutton
3. onSavedInstance >onPause >onStop
4. Readyour SMS
5. Executeaninstanceoftheapplication
6. onRestart >onStart >onResume
7. Youseethedataenteredinstep1
Application’sLifeCycle
Questions ?
Questions
?
50