Vous êtes sur la page 1sur 26

9/12/2011

1
Part3
Android
ApplicationsLifeCycle
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
U l ki A d id UnlockingAndroid
by Frank Ableson,Charlie Collins,and Robi Sen.
ISBN9781933988672
ManningPublications,2009.
Android Developers
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 definedintheapplication smanifestfile.Acomponentcanbeone
ofthefollowing:
1. AnActivity
2. AService
3. Abroadcastreceiver
4. Acontentprovider
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:FriedgerMffke(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:FriedgerMffke(friedger@openintents.org)
9/12/2011
3
3.Android Application'sLifeCycle
AndroidApplications
3.Broadcastreceiver
Abroadcastreceiver isacomponentthatdoesnothingbutreceiveandreactto
broadcastannouncements.
Manybroadcastsoriginateinsystemcode(eg.yougotmail)butanyother
applicationscanalsoinitiatebroadcasts.
Broadcastreceiversdonotdisplayauserinterface.However,theymaystartan
5
p y f , y y
activityinresponsetotheinformationtheyreceive,or asservicesdo they
mayusethenotificationmanagertoalerttheuser.
5
Reference:FriedgerMffke(friedger@openintents.org)
3.Android Application'sLifeCycle
AndroidApplications
4.Contentprovider
Acontentprovider makesaspecificsetoftheapplication'sdataavailableto
otherapplications.
Thedatausuallyisstoredinthefilesystem,orinanSQLitedatabase.
Thecontentproviderimplementsastandardsetofmethodsthatenableother
applicationstoretrieveandstoredataofthetypeitcontrols.
6
However,applicationsdonotcallthesemethodsdirectly.Rathertheyusea
contentresolverobjectandcallitsmethodsinstead.Acontentresolvercantalk
toanycontentprovider;itcooperateswiththeprovidertomanageany
interprocesscommunicationthat'sinvolved.
6
Reference:FriedgerMffke(friedger@openintents.org)
9/12/2011
4
3.Android Application'sLifeCycle
AndroidApplications
EveryAndroidapplicationrunsinitsownprocess
(with its own instance of the Dalvik virtual machine). (withitsowninstanceoftheDalvikvirtualmachine).
Wheneverthere'sarequestthatshouldbehandledbyaparticularcomponent,
Androidmakessurethattheapplicationprocessofthecomponentis
running,
startingitifnecessary,and
thatanappropriateinstanceofthecomponentisavailable,creatingthe
instanceifnecessary.
77
3.Android Application'sLifeCycle
ApplicationsLifeCycle
ALinuxprocessencapsulatinganAndroidapplicationiscreatedforthe p p g pp
applicationwhensomeofitscodeneedstoberun,andwillremain
runninguntil
1. itisnolongerneeded,OR
2. thesystemneedstoreclaimitsmemoryforusebyother
applications.
88
9/12/2011
5
3.Android Application'sLifeCycle
ApplicationsLifeCycle
AnunusualandfundamentalfeatureofAndroidisthat anapplication pp
process'slifetimeis not directlycontrolledbytheapplicationitself.
Instead,itisdeterminedbythesystemthroughacombinationof
1. thepartsoftheapplicationthatthesystemknowsarerunning,
2. howimportantthesethingsaretotheuser,and
3. how much overall memory is available in the system.
9
3. howmuchoverallmemoryisavailableinthesystem.
9
3.Android Application'sLifeCycle
ComponentLifecycles
Applicationcomponentshavea lifecycle
1. Abeginning whenAndroidinstantiatesthemtorespondto
intents
2. Anend whentheinstancesaredestroyed.
3. Inbetween,theymaysometimesbeactive orinactive,orinthe
caseofactivities visible totheuserorinvisible.
10 10
LifeasanAndroidApplication:
Active/Inactive
Visible/Invisible
Start
End
9/12/2011
6
3.Android Application'sLifeCycle
Activty Stack
Activitiesinthesystemaremanagedasanactivitystack. y g y
Whenanewactivityisstarted,itisplacedonthetop ofthe
stackandbecomestherunningactivity theprevious
activityalwaysremainsbelowitinthestack,andwillnot
cometotheforegroundagainuntilthenewactivityexits.
11 11
IftheuserpressestheBackButtonthenextactivityonthe
stackmovesupandbecomesactive.
3.Android Application'sLifeCycle
ActivityStack
NewActivity RunningActivity
LastRunning
Activity
Activityn1
. . .
NewActivity
started
Backbuttonpushedor
runningactivityclosed
Activity Stack
12 12
Activity1
Activity2
Activity3
... ActivityStack
Previous
Activities
Removedto
freeresources
Figure1.
9/12/2011
7
3.Android Application'sLifeCycle
LifeCycleStates
Anactivityhasessentially
threestates:
1. Itisactive orrunning
2. Itispaused or
3. Itisstopped .
13 13 Figure2.
3.Android Application'sLifeCycle
LifeCycleStates
Anactivityhasessentiallythreestates:
1. Itisactive orrunning whenitisintheforeground ofthescreen
(atthetopoftheactivitystackforthecurrenttask).
Thisistheactivitythatisthefocusfortheuser'sactions.
14 14 14
9/12/2011
8
3.Android Application'sLifeCycle
LifeCycleStates
An activityhasessentiallythreestates(cont.):
2. Itispaused ifithaslostfocusbutisstillvisibletotheuser.
Thatis,anotheractivityliesontopofitandthatnewactivityeitheris
transparent ordoesn'tcoverthefullscreen.
Apausedactivityiscompletelyalive (itmaintainsallstateandmember
informationandremainsattachedtothewindowmanager),butcanbe
15 15 15
g ),
killedbythesysteminextremelowmemorysituations.
3.Android Application'sLifeCycle
LifeCycleStates
Anactivityhasessentiallythreestates(cont.):
3. Itisstopped ifitiscompletelyobscured byanotheractivity.
Itstillretainsallstateandmemberinformation.However,itisnolonger
visibletotheusersoitswindowishiddenanditwilloftenbekilledby
thesystemwhenmemoryisneededelsewhere.
16 16 16
9/12/2011
9
3.Android Application'sLifeCycle
Applications
LifeCycle
17 17 Figure3.
3.Android Application'sLifeCycle
ApplicationsLifeCycle
Yourturn!
EXPERIMENT1.
Teachingnotes
1. WriteanAndroidapp.(PuraVida)toshowthedifferentcyclesfollowedbyan
application.
2. Themain.xmllayoutshouldincludeaButton(text:Finish,id:btnFinish)and
anEditText container(txt:andidtxtMsg).
3. UsetheonCreate methodtoconnectthebuttonandtextboxtotheprogram.
Addthefollowinglineofcode:
Toast . makeText(this, "onCreate", 1).show();
4. Theclickmethodhasonlyonecommand:finish(); calledtoterminatethe
18 18
application.AddaToastcommand(astheoneabove)toeachoftheremaining
sixmainevents.TosimplifyyourjobusetheEclipsestopmenu:Source>
Override/ImplementMethods
5. Ontheoptionwindowcheckmarkeachofthefollowingevents:onStart,
onResume,onPause,onStop,onDestry,onRestart
(noticehowmanyonEvent methodsarethere!!!)
6. Saveyourcode.
9/12/2011
10
3.Android Application'sLifeCycle
ApplicationsLifeCycle
Yourturn!
EXPERIMENT1(cont.)
Teachingnotes
7. Compileandexecuteapplication.
8. WritedownthesequenceofmessagesdisplayedbytheToastcommands.
9. PresstheFINISHbutton.Observethesequenceofstates.
10. Reexecutetheapplication
11. PressemulatorsHOMEbutton.Whathappens?
12. Clickonlaunchpad,lookforiconandreturntothePuraVidaapp.What
sequenceofmessagesisdisplayed?
13. ClickontheemulatorsCALL(Greenphone).Istheapppausedorstopped?
19 19
( p ) pp p pp
14. ClickontheBACKbuttontoreturntotheapplication.
15. LongtapontheemulatorsHANGUPbutton.Whathappens?
3.Android Application'sLifeCycle
ApplicationsLifeCycle
Yourturn!
EXPERIMENT2
Teachingnotes
7. Runasecondemulator.
1. Makeavoicecalltothefirstemulatorthatisstillshowingourapp.What
happensonthiscase?(realtimesynchronousrequest)
2. Sendatextmessagetofirstemulator(asynchronousattentionrequest)
8. WriteaphraseintheEditText box(thesearethebestmomentsofmylife.).
9. Reexecutetheapp.Whathappenedtothetext?
20 20
pp pp
9/12/2011
11
3.Android Application'sLifeCycle
ApplicationsLifeCycle
Yourturn!
EXPERIMENT3
Teachingnotes
Providedatapersistency.
18. UsetheonPause methodtoaddthefollowingfragment
Shar edPr ef er ences myFi l e1 = get Shar edPr ef er ences( " myFi l e1" ,
Act i vi t y. MODE_PRIVATE);
Shar edPr ef er ences. Edi t or myEdi t or = myFi l e1. edi t ( ) ;
St r i ng t emp = t xt Msg. get Text ( ) . t oSt r i ng( ) ;
myEdi t or . put St r i ng( " mydat a" , t emp) ;
myEdi t or . commi t ( ) ;
18 Use the onResume method to add the following frament
21 21
18. UsetheonResume methodtoaddthefollowingframent
Shar edPr ef er ences myFi l e = get Shar edPr ef er ences( "myFi l e1" ,
Act i vi t y. MODE_PRIVATE);
if ( (myFile != null) && (myFile.contains("mydata")) ) {
St r i ng t emp = myFi l e. get St r i ng( " mydat a", "***" ) ;
t xt Msg. set Text ( t emp) ;
}
19. Whathappensnowwiththedatapreviouslyenteredinthetextbox?
3.Android Application'sLifeCycle
LifeCycleEvents
Summary:APPMILESTONES
Ifanactivityispausedorstopped,thesystemcandropitfrommemoryeitherby
askingittofinish(callingitsfinish() method),orsimplykillingitsprocess.
Whenitisdisplayedagaintotheuser,itmustbecompletelyrestartedandrestored
toitspreviousstate.
Asanactivitytransitionsfromstatetostate,itisnotifiedofthechangebycallsto
thefollowingprotectedtransition methods:
22 22
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
23 23
ManyactivitieswillalsoimplementonPause() tocommitdata
changesandotherwisepreparetostopinteractingwiththeuser.
3.Android Application'sLifeCycle
ApplicationsLifetime
EntireLifetime t e et e
Theseventransitionmethods(Figure3)definetheentirelifecycleofan
activity.
Theentirelifetime ofanactivityhappensbetweenthefirstcallto
onCreate() throughtoasinglefinalcalltoonDestroy().
Anactivitydoesallitsinitialsetupof"global"stateinonCreate(),
24 24
andreleasesallremainingresourcesinonDestroy().
9/12/2011
13
3.Android Application'sLifeCycle
VisibleLifetime
VisibleLifetime s b e et e
Thevisiblelifetime ofanactivityhappensbetweenacalltoonStart() untila
correspondingcalltoonStop().
Duringthistime,theusercanseetheactivityonscreen,thoughit
maynotbeintheforegroundandinteractingwiththeuser.
TheonStart()andonStop()methodscanbecalledmultipletimes,
25 25
astheactivityalternatesbetweenbeingvisibleandhiddentothe
user.
Betweenthesetwomethods,youcanmaintainresourcesthatare
neededtoshowtheactivitytotheuser.
3.Android Application'sLifeCycle
ForegroundLifetime
ForegroundLifetime o eg ou d et e
Theforegroundlifetime ofanactivityhappensbetweenacallto
onResume() untilacorrespondingcallto onPause().
Duringthistime,theactivityisinfrontofallotheractivitiesonscreen
andisinteractingwiththeuser.
Anactivitycanfrequentlytransitionbetweentheresumed andpaused
26 26
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.
AlwaysfollowedbyonStart()
27 27
y y ()
3.Android Application'sLifeCycle
LifeCycleMethods
Method: onRestart()
Calledaftertheactivityhasbeenstopped,justpriortoitbeing
startedagain.
AlwaysfollowedbyonStart()
Method: onStart()
28 28
Calledjustbeforetheactivitybecomesvisibletotheuser.
FollowedbyonResume()iftheactivitycomestotheforeground,
oronStop()ifitbecomeshidden.
9/12/2011
15
3.Android Application'sLifeCycle
LifeCycleMethods
Method: onResume()
1. Calledjustbeforetheactivitystartsinteractingwiththeuser.
2. Atthispointtheactivityisatthetopoftheactivitystack,with
userinputgoingtoit.
3. AlwaysfollowedbyonPause().
29 29
3.Android Application'sLifeCycle
LifeCycleMethods
Method: onPause()
1. Calledwhenthesystemisabouttostartresuminganother
activity.
2. Thismethodistypicallyusedtocommit unsavedchangesto
persistentdata,stopanimationsandotherthingsthatmaybe
consumingCPU,andsoon.
3. Itshoulddowhateveritdoesveryquickly,becausethenext
30 30
y q y,
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
interactwiththeuser,orbyonDestroy()ifthisactivityisgoing
31 31
, y y() y g g
away.
4. Theactivityinthisstateiskillable bythesystem.
3.Android Application'sLifeCycle
LifeCycleMethods
Method: onDestroy()
1. Calledbeforetheactivityisdestroyed.
2. Thisisthefinalcallthattheactivitywillreceive.
3. Itcouldbecalledeitherbecausetheactivityisfinishing(someone
calledfinish() onit),orbecausethesystemistemporarily
destroyingthisinstanceoftheactivitytosavespace.
4. Youcandistinguishbetweenthesetwoscenarioswiththe
32 32
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 b f h
33 33
onPause()istheonlyonethatisguaranteedtobecalledbeforethe
processiskilled onStop()andonDestroy()maynotbe.
Therefore,youshoulduseonPause()towriteanypersistentdata
(suchasuseredits)tostorage.
Asanaside
AndroidPreferences
3.Android Application'sLifeCycle
LifeCycleMethods
Preferencesisalightweightmechanismtostoreandretrievekeyvalue pairsof
primitivedatatypes.Itistypicallyusedtostoreapplicationpreferences,such
asadefaultgreetingoratextfonttobeloadedwhenevertheapplicationis
started.
CallContext.getSharedPreferences() toreadandwritevalues.
Assignanametoyoursetofpreferencesifyouwanttosharethemwithother
componentsinthesameapplication,oruse Activity.getPreferences()withno
nametokeepthemprivatetothecallingactivity.
Youcannotsharepreferencesacrossapplications(exceptbyusingacontent
provider).
34 34
9/12/2011
18
3.Android Application'sLifeCycle
Example
LifeCycle
Example
LAYOUT
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/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"
d id l h i h " "
Thefollowingapplication
demonstratessomeof
thestatetransitioning
situationsexperiencedin
thelifecycleofatypical
Androidactivity.
android:layout_height="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>
/T Vi
35 35
</TextView>
<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 ci s493. l i f ecycl e
import andr oi d. app. Act i vi t y;
import andr oi d. cont ent . Shar edPr ef er ences;
import andr oi d. os. Bundl e;
import andr oi d. vi ew. Vi ew;
import andr oi d. wi dget . *;
//GOAL: show the following life-cycle events in action
/ / pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) ;
/ / t t d i d St t ( )
36 36
/ / pr ot ect ed voi d onSt ar t ( ) ;
/ / pr ot ect ed voi d onRest ar t ( ) ;
/ / pr ot ect ed voi d onResume( ) ;
/ / pr ot ect ed voi d onPause( ) ;
/ / pr ot ect ed voi d onSt op( ) ;
/ / pr ot ect ed voi d onDest r oy( ) ;
9/12/2011
19
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part1
public class GoodLife extends Activity { publicclassGoodLife extendsActivity{
//classvariablesandconstants
publicstaticfinalStringMYPREFSID ="MyPrefs001";
publicstaticfinalint actMode =Activity.MODE_PRIVATE;
LinearLayout myScreen;
EditText txtColorSelect;
TextView txtToDo;
37 37
Button btnFinish;
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part2
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
myScr een = ( Li near Layout ) f i ndVi ewByI d( R. i d. myScreen);
t xt ToDo = ( Text Vi ew) f i ndVi ewByI d( R. i d. txtToDo);
St r i ng msg = "I nst r uct i ons: \ n "
+ " 0. New i nst ance ( onCr eat e, onSt ar t , onResume) \ n "
+ " 1. Back Ar r ow ( onPause, onSt op, onDest r oy) \ n "
+ " 2. Fi ni sh ( onPause, onSt op, onDest r oy) \ n "
+ " 3. Home ( onPause, onSt op) \ n "
+ " 4. Af t er 3 > App Tab > r e- execut e cur r ent app \ n "
38 38
pp pp
+ " ( onRest ar t , onSt ar t , onResume) \ n "
+ " 5. Run DDMS > Recei ve a phone cal l or SMS \ n "
+ " ( onRest ar t , onSt ar t , onResume) \ n "
+ " 6. Ent er some dat a - r epeat st eps 1- 5 \ n " ;
t xt ToDo. set Text ( msg) ;
9/12/2011
20
Code:LifeCycleDemo.Part2
t xt Col or Sel ect = ( Edi t Text ) f i ndVi ewByI d( R. i d. txtColorSelect);
/ / you may want t o ski p di scussi ng t he l i st ener unt i l l at er
l l dd h d i ( t t h (){
3.Android Application'sLifeCycle
Example:LifeCycle
t xt Col or Sel ect . addText ChangedLi st ener ( new TextWatcher(){
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());
}
}) ;
bt nFi ni sh = ( But t on) f i ndVi ewByI d( R. i d. btnFinish);
bt nFi ni sh. set OnCl i ckLi st ener ( new OnClickListener() {
public void onClick(View arg0) {
f i ni sh( ) ;
}
}) ;
Toast . makeText(getApplicationContext(), "onCreate", 1).show();
}
39 39
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part3
@Over r i de
protected void onPause() {
super.onPause();
saveDat aFr omCur r ent St at e( ) ;
Toast . makeText(this, "onPause", 1).show();
}
@Over r i de
protected void onRestart() {
super.onRestart();
Toast . makeText(this, "onRestart", 1).show();
}
40 40
}
@Over r i de
protected void onResume() {
super.onResume();
Toast . makeText(this, "onResume", 1).show();
}
9/12/2011
21
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part4
@Over r i de
protected void onStart() {
/ / TODO Auto-generated method stub
super.onStart();
updat eFr omSavedSt at e( ) ;
Toast . makeText(this, "onStart", 1).show();
}
@Over r i de
protected void onDestroy() {
/ / TODO Auto-generated method stub
super.onDestroy();
41 41
Toast . makeText(this, "onDestroy", 1).show();
}
@Over r i de
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() {
Shar edPr ef er ences myPr ef s = get Shar edPr ef er ences( MYPREFSID, actMode);
h d f di di f di ( ) Shar edPr ef er ences. Edi t or myEdi t or = myPr ef s. edi t ( ) ;
myEdi t or . put St r i ng( " myBkCol or " , t xt Col or Sel ect . get Text ( ) . t oSt r i ng( ) ) ;
myEdi t or . commi t ( ) ;
}/ / saveDat aFr omCur r ent St at e
protected void updateFromSavedState() {
Shar edPr ef er ences myPr ef s = get Shar edPr ef er ences( MYPREFSID, actMode);
if ((myPrefs != null) && (myPrefs.contains("myBkColor"))) {
St r i ng t heChosenCol or = myPr ef s. get St r i ng( "myBkCol or " , " ") ;
t xt Col or Sel ect . set Text ( t heChosenCol or ) ;
42 42
changeBackgr oundCol or ( t heChosenCol or ) ;
}
}/ / Updat eFr omSavedSt at e
protected void clearMyPreferences() {
Shar edPr ef er ences myPr ef s = get Shar edPr ef er ences( MYPREFSID, actMode);
Shar edPr ef er ences. Edi t or myEdi t or = myPr ef s. edi t ( ) ;
myEdi t or . cl ear ( ) ;
myEdi t or . commi t ( ) ;
}
9/12/2011
22
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part6
private void changeBackgroundColor (String theChosenColor){
/ / h b k d l / / change backgr ound col or
if (theChosenColor.contains("red"))
myScr een. set Backgr oundCol or ( 0xf f f f 0000) ;
else if (theChosenColor.contains("green"))
myScr een. set Backgr oundCol or ( 0xf f 00f f 00) ;
else if (theChosenColor.contains("blue"))
myScr een. set Backgr oundCol or ( 0xf f 0000f f ) ;
else {
/ / r eset i ng user pr ef er ences
cl ear MyPr ef er ences( ) ;
myScr een. set Backgr oundCol or ( 0xf f 000000) ;
43 43
}
}
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part8
/*
protectedvoidonRestoreInstanceState(BundlesavedInstanceState)
ThismethodiscalledafteronStart()whentheactivityisbeingreinitialized
fromapreviouslysavedstate.
Thedefaultimplementationofthismethodperformsarestoreofanyviewstate
thathadpreviouslybeenfrozenbyonSaveInstanceState(Bundle).
*/
@Over r i de
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast . makeText(getBaseContext(),
"onRestoreInstanceState ...BUNDLING",
44 44
,
Toast . LENGTH_LONG).show();
}
9/12/2011
23
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part9
/*
d id ( dl ) protectedvoidonSaveInstanceState(BundleoutState)
Calledtoretrieveperinstancestatefromanactivitybeforebeingkilled
sothatthestatecanberestoredin
onCreate(Bundle)or
onRestoreInstanceState(Bundle)(theBundlepopulatedbythismethod
willbepassedtoboth).
Thismethodiscalledbeforeanactivitymaybekilledsothatwhenitcomes
backsometimeinthefutureitcanrestoreitsstate.Forexample,ifactivityB
islaunchedinfrontofactivityA,andatsomepointactivityAiskilledto
reclaimresources,activityAwillhaveachancetosavethecurrentstateof
45 45
y f
itsuserinterfaceviathismethodsothatwhentheuserreturnstoactivityA,
thestateoftheuserinterfacecanberestoredvia:
onCreate(Bundle)oronRestoreInstanceState(Bundle).
*/
3.Android Application'sLifeCycle
Example:LifeCycle
Code:LifeCycleDemo.Part10
@Over r i de
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast . makeText(getBaseContext(),
"onSaveInstanceState ...BUNDLING",
Toast . LENGTH_LONG).show();
} / / onSaveI nst anceSt at e
}/ / Lyf eCi cl eDemo
46 46
9/12/2011
24
3.Android Application'sLifeCycle
Example:LifeCycle
onCreate onStart onResume
47 47
3.Android Application'sLifeCycle
Example:LifeCycle
onPause onStop onDestroy
48 48
AfterpressingBackArrow
9/12/2011
25
3.Android Application'sLifeCycle
Example:LifeCycle
After
pressingHome
After
reexecutingAndLife2
After
BackArroworFinish
onSavedInstanceState >
onPause >
onStop >
onRestart >
onStart >
onResume >
onPause >
onStop >
onDestroy >
PreservingStateInformation
1 Enter data: Hasta la vista!
49 49
EndofExample
1. Enter data: Hasta lavista!
2. ClickHomebutton
3. onSavedInstance >onPause >onStop
4. Readyour SMS
5. Executeaninstanceoftheapplication
6. onRestart >onStart >onResume
7. Youseethedataenteredinstep1
ApplicationsLifeCycle
Questions ? Questions?
50
9/12/2011
26
ApplicationsLifeCycle
Appendix Appendix
SavingState
@Override
publicvoidonCreate(BundlesavedInstanceState){
...somevalue =savedInstanceState.getString(SOME_KEY);
...
51
}
...
@OverrideprotectedvoidonSaveInstanceState(BundleoutState){
super.onSaveInstanceState(outState);
outState.putString(SOME_KEY,"blahblah blah");
}

Vous aimerez peut-être aussi