Android Chapter03 Life Cycle

  • Upload
    letuyen

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

  • 9/12/2011

    1

    Part3

    AndroidApplicationsLifeCycle

    VictorMatosClevelandStateUniversity

    Notesarebasedon:U l ki A d idUnlockingAndroidbyFrankAbleson,CharlieCollins,andRobi Sen.ISBN9781933988672ManningPublications,2009.AndroidDevelopershttp://developer.android.com/index.html

    3.Android Application'sLifeCycle

    AndroidApplicationsAnapplicationconsistsofoneormorecomponents thataredefined in the application's manifest file. A component can be onedefinedintheapplication smanifestfile.Acomponentcanbeoneofthefollowing:

    1. AnActivity2. AService3. Abroadcastreceiver4. Acontentprovider

    22

  • 9/12/2011

    2

    3.Android Application'sLifeCycle

    AndroidApplications1.ActivityAnactivity usuallypresentsasinglevisualuserinterfacefromwhichanumberofactionscouldbeperformed.Altoughactivitiesworktogethertoformacohesiveuserinterface,eachactivityisindependentoftheothers.Typically,oneoftheactivitiesismarkedasthefirst onethatshouldbepresented

    3

    totheuserwhentheapplicationislaunched.Movingfromoneactivitytoanotherisaccomplishedbyhavingthecurrentactivitystartthenextonethroughsocalledintents.

    3Reference:FriedgerMffke([email protected])

    3.Android Application'sLifeCycle

    AndroidApplications2.ServiceAservicedoesn'thaveavisualuserinterface,butratherrunsinthebackgroundforanindefiniteperiodoftime.It'spossibletoconnectto(bindto)anongoingservice(andstarttheserviceifit'snotalreadyrunning).

    4

    Whileconnected,youcancommunicatewiththeservicethroughaninterfacethattheserviceexposes.

    4Reference:FriedgerMffke([email protected])

  • 9/12/2011

    3

    3.Android Application'sLifeCycle

    AndroidApplications3.BroadcastreceiverAbroadcastreceiver isacomponentthatdoesnothingbutreceiveandreacttobroadcastannouncements.Manybroadcastsoriginateinsystemcode(eg.yougotmail)butanyotherapplicationscanalsoinitiatebroadcasts.Broadcastreceiversdonotdisplayauserinterface.However,theymaystartan

    5

    p y f , y yactivityinresponsetotheinformationtheyreceive,or asservicesdo theymayusethenotificationmanagertoalerttheuser.

    5Reference:FriedgerMffke([email protected])

    3.Android Application'sLifeCycle

    AndroidApplications4.ContentproviderAcontentprovidermakesaspecificsetoftheapplication'sdataavailabletootherapplications.Thedatausuallyisstoredinthefilesystem,orinanSQLitedatabase.Thecontentproviderimplementsastandardsetofmethodsthatenableotherapplicationstoretrieveandstoredataofthetypeitcontrols.

    6

    However,applicationsdonotcallthesemethodsdirectly.Rathertheyuseacontentresolverobjectandcallitsmethodsinstead.Acontentresolvercantalktoanycontentprovider;itcooperateswiththeprovidertomanageanyinterprocesscommunicationthat'sinvolved.

    6Reference:FriedgerMffke([email protected])

  • 9/12/2011

    4

    3.Android Application'sLifeCycle

    AndroidApplicationsEveryAndroidapplicationrunsinitsownprocess(with its own instance of the Dalvik virtual machine).(withitsowninstanceoftheDalvikvirtualmachine).Wheneverthere'sarequestthatshouldbehandledbyaparticularcomponent,

    Androidmakessurethattheapplicationprocessofthecomponentisrunning,

    startingitifnecessary,and thatanappropriateinstanceofthecomponentisavailable,creatingthe

    instanceifnecessary.

    77

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleALinuxprocessencapsulatinganAndroidapplicationiscreatedforthep p g ppapplicationwhensomeofitscodeneedstoberun,andwillremainrunninguntil

    1. itisnolongerneeded,OR2. thesystemneedstoreclaimitsmemoryforusebyother

    applications.

    88

  • 9/12/2011

    5

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleAnunusualandfundamentalfeatureofAndroidisthat anapplicationppprocess'slifetimeis not directlycontrolledbytheapplicationitself.Instead,itisdeterminedbythesystemthroughacombinationof

    1. thepartsoftheapplicationthatthesystemknowsarerunning,2. howimportantthesethingsaretotheuser,and3. how much overall memory is available in the system.

    9

    3. howmuchoverallmemoryisavailableinthesystem.

    9

    3.Android Application'sLifeCycle

    ComponentLifecyclesApplicationcomponentshavea lifecycle1. Abeginning whenAndroidinstantiatesthemtorespondto

    intents2. Anend whentheinstancesaredestroyed.3. Inbetween,theymaysometimesbeactive orinactive,orinthe

    caseofactivities visible totheuserorinvisible.

    1010

    LifeasanAndroidApplication:Active/InactiveVisible/Invisible

    Start End

  • 9/12/2011

    6

    3.Android Application'sLifeCycle

    Activty Stack

    Activitiesinthesystemaremanagedasanactivitystack.y g y Whenanewactivityisstarted,itisplacedonthetop ofthe

    stackandbecomestherunningactivity thepreviousactivityalwaysremainsbelowitinthestack,andwillnotcometotheforegroundagainuntilthenewactivityexits.

    1111

    IftheuserpressestheBackButtonthenextactivityonthestackmovesupandbecomesactive.

    3.Android Application'sLifeCycle

    ActivityStackNewActivity RunningActivity

    LastRunningActivity

    Activityn1. . .

    NewActivitystarted

    Backbuttonpushedorrunningactivityclosed

    Activity Stack

    1212

    Activity1Activity2Activity3...ActivityStack

    PreviousActivities Removedto

    freeresources

    Figure1.

  • 9/12/2011

    7

    3.Android Application'sLifeCycleLifeCycleStates

    Anactivityhasessentiallythreestates:1. Itisactive orrunning2. Itispaused or3. Itisstopped .

    1313Figure2.

    3.Android Application'sLifeCycle

    LifeCycleStatesAnactivityhasessentiallythreestates:

    1. Itisactive orrunningwhenitisintheforeground ofthescreen(atthetopoftheactivitystackforthecurrenttask).Thisistheactivitythatisthefocusfortheuser'sactions.

    141414

  • 9/12/2011

    8

    3.Android Application'sLifeCycle

    LifeCycleStatesAn activityhasessentiallythreestates(cont.):

    2. Itispaused ifithaslostfocusbutisstillvisibletotheuser.Thatis,anotheractivityliesontopofitandthatnewactivityeitheristransparent ordoesn'tcoverthefullscreen.Apausedactivityiscompletelyalive (itmaintainsallstateandmemberinformationandremainsattachedtothewindowmanager),butcanbe

    151515

    g ),killedbythesysteminextremelowmemorysituations.

    3.Android Application'sLifeCycle

    LifeCycleStatesAnactivityhasessentiallythreestates(cont.):

    3. Itisstopped ifitiscompletelyobscured byanotheractivity.Itstillretainsallstateandmemberinformation.However,itisnolongervisibletotheusersoitswindowishiddenanditwilloftenbekilledbythesystemwhenmemoryisneededelsewhere.

    161616

  • 9/12/2011

    9

    3.Android Application'sLifeCycle

    ApplicationsLifeCycle

    1717Figure3.

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleYourturn!EXPERIMENT1. Teachingnotes1. 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

    1818

    application.AddaToastcommand(astheoneabove)toeachoftheremainingsixmainevents.TosimplifyyourjobusetheEclipsestopmenu:Source>Override/ImplementMethods

    5. Ontheoptionwindowcheckmarkeachofthefollowingevents:onStart,onResume,onPause,onStop,onDestry,onRestart(noticehowmanyonEventmethodsarethere!!!)

    6. Saveyourcode.

  • 9/12/2011

    10

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleYourturn!EXPERIMENT1(cont.) Teachingnotes7. Compileandexecuteapplication.8. WritedownthesequenceofmessagesdisplayedbytheToastcommands.9. PresstheFINISHbutton.Observethesequenceofstates.10. Reexecutetheapplication11. PressemulatorsHOMEbutton.Whathappens?12. Clickonlaunchpad,lookforiconandreturntothePuraVidaapp.What

    sequenceofmessagesisdisplayed?13. ClickontheemulatorsCALL(Greenphone).Istheapppausedorstopped?

    1919

    ( p ) pp p pp14. ClickontheBACKbuttontoreturntotheapplication.15. LongtapontheemulatorsHANGUPbutton.Whathappens?

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleYourturn!EXPERIMENT2 Teachingnotes7. Runasecondemulator.

    1. Makeavoicecalltothefirstemulatorthatisstillshowingourapp.Whathappensonthiscase?(realtimesynchronousrequest)

    2. Sendatextmessagetofirstemulator(asynchronousattentionrequest)8. WriteaphraseintheEditText box(thesearethebestmomentsofmylife.).9. Reexecutetheapp.Whathappenedtothetext?

    2020

    pp pp

  • 9/12/2011

    11

    3.Android Application'sLifeCycle

    ApplicationsLifeCycleYourturn!EXPERIMENT3 TeachingnotesProvidedatapersistency.18. UsetheonPausemethodtoaddthefollowingfragment

    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 onResumemethod to add the following frament

    2121

    18. UsetheonResumemethodtoaddthefollowingframentSharedPreferences 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

    LifeCycleEventsSummary:APPMILESTONESIfanactivityispausedorstopped,thesystemcandropitfrommemoryeitherbyaskingittofinish(callingitsfinish() method),orsimplykillingitsprocess.Whenitisdisplayedagaintotheuser,itmustbecompletelyrestartedandrestoredtoitspreviousstate.Asanactivitytransitionsfromstatetostate,itisnotifiedofthechangebycallstothefollowingprotectedtransitionmethods:

    2222

    voidonCreate(BundlesavedInstanceState)voidonStart()voidonRestart()voidonResume()

    voidonPause()voidonStop()voidonDestroy()

  • 9/12/2011

    12

    3.Android Application'sLifeCycle

    LifeCycleEventsAllofthesemethodsarehooks thatyoucanoverridetodoappropriateworkwhenthestatechanges.

    (MUST)AllactivitiesmustimplementonCreate() todotheinitialsetupwhentheobjectisfirstinstantiated.(HighlyRecommended)Many activities will also implement onPause() to commit data

    2323

    ManyactivitieswillalsoimplementonPause() tocommitdatachangesandotherwisepreparetostopinteractingwiththeuser.

    3.Android Application'sLifeCycle

    ApplicationsLifetimeEntireLifetimet e et eTheseventransitionmethods(Figure3)definetheentirelifecycleofanactivity.

    Theentirelifetime ofanactivityhappensbetweenthefirstcalltoonCreate() throughtoasinglefinalcalltoonDestroy().

    Anactivitydoesallitsinitialsetupof"global"stateinonCreate(),

    2424

    andreleasesallremainingresourcesinonDestroy().

  • 9/12/2011

    13

    3.Android Application'sLifeCycle

    VisibleLifetimeVisibleLifetimes b e et eThevisiblelifetime ofanactivityhappensbetweenacalltoonStart() untilacorrespondingcalltoonStop().

    Duringthistime,theusercanseetheactivityonscreen,thoughitmaynotbeintheforegroundandinteractingwiththeuser.

    TheonStart()andonStop()methodscanbecalledmultipletimes,

    2525

    astheactivityalternatesbetweenbeingvisibleandhiddentotheuser.

    Betweenthesetwomethods,youcanmaintainresourcesthatareneededtoshowtheactivitytotheuser.

    3.Android Application'sLifeCycle

    ForegroundLifetimeForegroundLifetimeo eg ou d et eTheforegroundlifetime ofanactivityhappensbetweenacalltoonResume() untilacorrespondingcallto onPause().

    Duringthistime,theactivityisinfrontofallotheractivitiesonscreenandisinteractingwiththeuser.

    Anactivitycanfrequentlytransitionbetweentheresumed andpaused

    2626

    states forexample, onPause()iscalledwhenthedevicegoestosleeporwhenanew

    activityisstarted, onResume()iscalledwhenanactivityresultoranewintentis

    delivered.

  • 9/12/2011

    14

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onCreate()

    Calledwhentheactivityisfirstcreated. Thisiswhereyoushoulddoallofyournormalstaticsetup

    createviews,binddatatolists,andsoon. ThismethodispassedaBundle objectcontainingtheactivity's

    previousstate,ifthatstatewascaptured. AlwaysfollowedbyonStart()

    2727

    y y ()

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onRestart()

    Calledaftertheactivityhasbeenstopped,justpriortoitbeingstartedagain.

    AlwaysfollowedbyonStart()

    Method: onStart()

    2828

    Calledjustbeforetheactivitybecomesvisibletotheuser. FollowedbyonResume()iftheactivitycomestotheforeground,

    oronStop()ifitbecomeshidden.

  • 9/12/2011

    15

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onResume()

    1. Calledjustbeforetheactivitystartsinteractingwiththeuser.2. Atthispointtheactivityisatthetopoftheactivitystack,with

    userinputgoingtoit.3. AlwaysfollowedbyonPause().

    2929

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onPause()

    1. Calledwhenthesystemisabouttostartresuminganotheractivity.

    2. Thismethodistypicallyusedtocommit unsavedchangestopersistentdata,stopanimationsandotherthingsthatmaybeconsumingCPU,andsoon.

    3. Itshoulddowhateveritdoesveryquickly,becausethenext

    3030

    y q y,activitywillnotberesumeduntilitreturns.

    4. FollowedeitherbyonResume()iftheactivityreturnsbacktothefront,orbyonStop()ifitbecomesinvisibletotheuser.

    5. Theactivityinthisstateiskillable bythesystem.

  • 9/12/2011

    16

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onStop()

    1. Calledwhentheactivityisnolongervisibletotheuser.2. Thismayhappenbecauseitisbeingdestroyed,orbecause

    anotheractivity(eitheranexistingoneoranewone)hasbeenresumedandiscoveringit.

    3. FollowedeitherbyonRestart()iftheactivityiscomingbacktointeractwiththeuser,orbyonDestroy()ifthisactivityisgoing

    3131

    , y y() y g gaway.

    4. Theactivityinthisstateiskillable bythesystem.

    3.Android Application'sLifeCycle

    LifeCycleMethodsMethod: onDestroy()

    1. Calledbeforetheactivityisdestroyed.2. Thisisthefinalcallthattheactivitywillreceive.3. Itcouldbecalledeitherbecausetheactivityisfinishing(someone

    calledfinish() onit),orbecausethesystemistemporarilydestroyingthisinstanceoftheactivitytosavespace.

    4. Youcandistinguishbetweenthesetwoscenarioswiththe

    3232

    gisFinishing()method.

    5. Theactivityinthisstateiskillable bythesystem.

  • 9/12/2011

    17

    3.Android Application'sLifeCycle

    LifeCycleMethodsKillableStates Activitiesonkillablestatescanbeterminatedbythesystematany

    timeafterthemethodreturns,withoutexecutinganotherlineoftheactivity'scode.

    Threemethods(onPause(),onStop(),andonDestroy())arekillable.() h l h d b ll d b f h

    3333

    onPause()istheonlyonethatisguaranteedtobecalledbeforetheprocessiskilled onStop()andonDestroy()maynotbe.

    Therefore,youshoulduseonPause()towriteanypersistentdata(suchasuseredits)tostorage.

    AsanasideAndroidPreferences

    3.Android Application'sLifeCycle

    LifeCycleMethods

    Preferencesisalightweightmechanismtostoreandretrievekeyvalue pairsofprimitivedatatypes.Itistypicallyusedtostoreapplicationpreferences,suchasadefaultgreetingoratextfonttobeloadedwhenevertheapplicationisstarted.CallContext.getSharedPreferences() toreadandwritevalues.Assignanametoyoursetofpreferencesifyouwanttosharethemwithothercomponentsinthesameapplication,oruse Activity.getPreferences()withnonametokeepthemprivatetothecallingactivity.Youcannotsharepreferencesacrossapplications(exceptbyusingacontentprovider). 3434

  • 9/12/2011

    18

    3.Android Application'sLifeCycle

    ExampleLifeCycleExample

    LAYOUT

    /T Vi

    3535

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part1Package cis493.lifecycleimport 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

    //protected void onStart();//protected void onRestart();//protected void onResume();//protected void onPause();//protected void onStop();//protected void onDestroy();

  • 9/12/2011

    19

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part1

    public class GoodLife extends Activity {publicclassGoodLife extendsActivity{//classvariablesandconstantspublicstaticfinalStringMYPREFSID ="MyPrefs001";publicstaticfinalint actMode =Activity.MODE_PRIVATE;LinearLayout myScreen;EditText txtColorSelect;TextView txtToDo;

    3737

    Button btnFinish;

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part2

    @Overridepublic 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 > App Tab > re-execute current app \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.Part2txtColorSelect = (EditText) findViewById(R.id.txtColorSelect);// you may want to skip discussing the listener until later

    l l dd h d i ( t t h (){

    3.Android Application'sLifeCycle

    Example:LifeCycletxtColorSelect.addTextChangedListener(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());

    }});

    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:LifeCycleCode:LifeCycleDemo.Part3

    @Overrideprotected void onPause() {

    super.onPause();saveDataFromCurrentState();Toast.makeText(this, "onPause", 1).show();

    }

    @Overrideprotected void onRestart() {

    super.onRestart();Toast.makeText(this, "onRestart", 1).show();

    }

    4040

    }

    @Overrideprotected void onResume() {

    super.onResume();Toast.makeText(this, "onResume", 1).show();

    }

  • 9/12/2011

    21

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part4@Overrideprotected void onStart() {

    // TODO Auto-generated method stubsuper.onStart();updateFromSavedState();Toast.makeText(this, "onStart", 1).show();

    }

    @Overrideprotected void onDestroy() {

    // TODO Auto-generated method stubsuper.onDestroy();

    4141

    Toast.makeText(this, "onDestroy", 1).show();}

    @Overrideprotected void onStop() {// TODO Auto-generated method stubsuper.onStop();Toast.makeText(this, "onStop", 1).show();

    }

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part5protected void saveDataFromCurrentState() {

    SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);h d f di di f di ()SharedPreferences.Editor myEditor = myPrefs.edit();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(theChosenColor);

    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:LifeCycleCode:LifeCycleDemo.Part6private void changeBackgroundColor (String theChosenColor){

    // h b k d l// change background colorif (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 preferencesclearMyPreferences();myScreen.setBackgroundColor(0xff000000);

    4343

    }}

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part8

    /*protectedvoidonRestoreInstanceState(BundlesavedInstanceState)ThismethodiscalledafteronStart()whentheactivityisbeingreinitializedfromapreviouslysavedstate.ThedefaultimplementationofthismethodperformsarestoreofanyviewstatethathadpreviouslybeenfrozenbyonSaveInstanceState(Bundle).*/@Overrideprotected 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:LifeCycleCode:LifeCycleDemo.Part9/*

    d id ( dl )protectedvoidonSaveInstanceState(BundleoutState)Calledtoretrieveperinstancestatefromanactivitybeforebeingkilledsothatthestatecanberestoredin

    onCreate(Bundle)oronRestoreInstanceState(Bundle)(theBundlepopulatedbythismethod

    willbepassedtoboth).Thismethodiscalledbeforeanactivitymaybekilledsothatwhenitcomesbacksometimeinthefutureitcanrestoreitsstate.Forexample,ifactivityBislaunchedinfrontofactivityA,andatsomepointactivityAiskilledtoreclaimresources,activityAwillhaveachancetosavethecurrentstateof

    4545

    y fitsuserinterfaceviathismethodsothatwhentheuserreturnstoactivityA,thestateoftheuserinterfacecanberestoredvia:onCreate(Bundle)oronRestoreInstanceState(Bundle).*/

    3.Android Application'sLifeCycle

    Example:LifeCycleCode:LifeCycleDemo.Part10

    @Overrideprotected 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:LifeCycleonCreate onStart onResume

    4747

    3.Android Application'sLifeCycle

    Example:LifeCycleonPause onStop onDestroy

    4848AfterpressingBackArrow

  • 9/12/2011

    25

    3.Android Application'sLifeCycle

    Example:LifeCycleAfterpressingHome

    AfterreexecutingAndLife2

    AfterBackArroworFinish

    onSavedInstanceState >onPause >onStop >

    onRestart >onStart >onResume >

    onPause >onStop >onDestroy >

    PreservingStateInformation1 Enter data: Hasta la vista!

    4949

    EndofExample

    1. Enter data: Hasta lavista!2. ClickHomebutton3. onSavedInstance >onPause >onStop4. Readyour SMS5. Executeaninstanceoftheapplication6. onRestart >onStart >onResume7. Youseethedataenteredinstep1

    ApplicationsLifeCycleQuestions ?Questions?

    50

  • 9/12/2011

    26

    ApplicationsLifeCycleAppendixAppendixSavingState

    @OverridepublicvoidonCreate(BundlesavedInstanceState){

    ...somevalue =savedInstanceState.getString(SOME_KEY);

    ...

    51

    }...@OverrideprotectedvoidonSaveInstanceState(BundleoutState){

    super.onSaveInstanceState(outState);outState.putString(SOME_KEY,"blahblah blah");

    }