版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
AndroidAndroidapplicationpackage(APK)isthepackagefileformatusedtodistributeandinstallapplicationsoftwareontoAndroid.DalvikA
virtualmachine
optimizedformobiledevicesthatwasdesignedandwrittenbyDanBornsteinandotherGoogleengineers.Dalvikisapartofthe
software
stack
thatmakesupthe
Androidplatform.AccordingtoGoogle’sAndroiddocumentation,theDalvikVMisaninterpreter-onlyvirtualmachinethatexecutesfilesintheDalvikExecutable(.dex)format,aformatthatisoptimizedforefficientstorageandmemory-mappableexecution.Thevirtualmachineisregister-based,anditcanrunclassescompiledbya
Java
languagecompilerthathavebeentransformedintoitsnativeformat.DalvikVirtualMachineisaRegister-Basedvirtualmachine.ItwasdesignedandwrittenbyDanBornsteinwithcontributionsofotherGoogleengineersaspartoftheAndroidmobilephoneplatform.TheDalvikvirtualmachinewasnamedafterBornsteinafterthefishingvillage“Dalvík”inEyjafj?reur,Iceland,wheresomeofhisancestorsusedtolive.WorkingofDVMTheJavaCompiler(javac)convertstheJavaSourceCodeintoJavaByte-Code(.class).ThenDEXCompilerconvertsthis(.class)fileintoinDalvikByteCodei.e.“.dex”file.ApplicationForAndroid,anewVirtualmachinewasdevelopedbyGoogleasstatedabove.ItusesregistersoftheCPUtostoretheoperands.Sonorequirementofanypushingandpoppingofinstructions.Hencemakingexecutionfaster.Theinstructionsoperateonvirtualregisters,beingthosevirtualregistersmemorypositionsinthehostdevice.Register-basedmodelsaregoodatoptimizingandrunningonlowmemory.Theycanstorecommonsub-expressionresultswhichcanbeusedagaininthefuture.ThisisnotpossibleinaStack-basedmodelatall.DalvikVirtualMachineusesitsownbyte-codeandruns“.dex”(DalvikExecutableFile)file.AdvantagesDVMsupportstheAndroidoperatingsystemonly.InDVMexecutableisAPK.Executionisfaster.FromAndroid2.2SDKDalvikhasit’sownJIT(JustInTime)compiler.DVMhasbeendesignedsothatadevicecanrunmultipleinstancesoftheVirtualMachineeffectively.Applicationsaregiventheirowninstances.DisadvantagesDVMsupportsonlyAndroidOperatingSystem.ForDVMveryfewRe-Toolsareavailable.Requiresmoreinstructionsthanregistermachinestoimplementthesamehigh-levelcode.AppInstallationtakesmoretimeduetodex.Moreinternalstorageisrequired.DifferencebetweenARTandDalvikApproach:
ARTusesAOT(AheadOfTime)approachandcompilesthewholecodeduringtheinstallationtimebuttheDalvikusesJIT(JustInTime)approachandcompliesonlyapartofthecodeduringinstallationandrestofthecodewillbecompileddynamically.Bootingtime:
AscomparetoDalvik,ARTtakesmoretimetorebootbecausethecacheisbuiltatthefirsttime.So,thebootingisslow.Space:
SinceARTusestheAOTapproach,soitneedsmorespaceduringinstallation.WhileDalvikusestheJITapproach,soformobilephoneshavinglessstoragecanusetheDalvik.Battery:
ARTincreasesbatteryperformancetoalargeextentbecauseoftheAOTapproach.WhiletheDalvikusestheJITapproachandthisresultsinmorebatteryutilization.GarbageCollection:
ARThasbettergarbagecollectionthanDalvik.So,DVMusesJITandhavealotofdrawbacksthatwerereplacedbyART.So,fromAndroid4.4(Kitkat)ARTwasintroducedasruntimeandfinallyfromAndroid5.0(Lollipop),theDalvikwascompletelyreplacedbyARTbyAndroid.Android:DVMvsARTVirtualMachineLetusclearupthedifferencebetweenJVMandDVMfirst.JavaVirtualMachine
isavirtualmachinecapableofexecutingJavabytecoderegardlessofthebaseplatform.Itisbasedontheprinciple"Writeonce,runanywhere."TheJavabytecodecanrunonanymachinecapableofsupportingJVM.TheJavacompilerconverts.javafilesintoclassfiles(bytecode).ThebytecodeispassedtoJVM,whichcompilesitintomachinecodeforexecutiondirectlyontheCPU.JVMfeatures:Stackarchitecture.Thestackisusedasadatastructurewheremethodsareplacedandstored.ItworksbytheLIFOschemeor"Lastin-FirstOut."Runs.classfilesonly.UsesaJITcompiler.DalvikVirtualMachine
(DVM)isaJavavirtualmachinedevelopedandwrittenbyDanBornsteinandothersaspartoftheAndroidmobileplatform.WecansaythatDalvikisaruntimeforAndroidoperatingsystemcomponentsanduserapplications.Eachprocessisexecutedinitsisolateddomain.Whenauserstartsanapp(ortheoperatingsystemlaunchesoneofitscomponents),theDalvikvirtualmachinekernel(ZygoteDalvikVM)createsaseparate,secureprocessinsharedmemory,whereVMisdirectlydeployedastheenvironmenttoruntheapplication.Inshort,AndroidwithinlookslikeasetofDalvikvirtualmachines,withexecutinganappineach.DVMfeatures:Register-basedarchitecture.Thedatastructurewithmethodsplacedthereisbasedonprocessorregisters.DuetoPOPandPUSHabsence,instructionsinregisterVMareexecutedfasterthansimilaronesinstackVMExecutesthebytecodeofitsformat.Androiddexer(we'lltalkaboutitlater)converts.classfilesinto.dexformatoptimizedforDVMexecution.Unlikea.classfile,a.dexfilecontainsseveralclassesatonce.
AndroidDexerAcrucialstepincreatinganAPKisconvertingtheJavabytecodeto.dexbytecodeforAndroidRuntimeandAndroiddeveloperstoknowaboutit.Thedexcompilermainlyworks"undercover"inroutineapplicationdevelopment,butitdirectlyaffectstheapplicationbuildtime,.dexfilesize,andruntimeperformance.Asalreadymentioned,the.dexfileitselfcontainsseveralclassesatonce.Repeatingstringsandotherconstants,usedinmultiple.classfiles,areincludedonlytosavespace.JavabytecodeisalsoconvertedtoanalternativecommandsetusedbyDVM.Anuncompressed.dexfileisusuallyafewpercentsmallerthanacompressedJavaarchive(JAR)fromthesame.classfiles.Initially,.classfileswereconvertedto.dexusingthebuilt-inDXcompiler.Butstartingfrom
AndroidStudio3.1
onwards,thedefaultcompilerwas
D8.ComparedtotheDXcompiler,theD8compilesfasterandoutputssmaller.dexfiles,providinghighapplicationperformanceduringruntime.Theresultingbytecodeisminifiedusinganopen-sourceutility
ProGuard.Asaresult,wegetthesame.dexfile,butsmaller.ThenthisfileisusedforAPKbuildingandfinallyfordeployingitontheAndroiddevice.
AftertheD8in
2018
came
R8,whichisessentiallythesameD8,butupdated.WhenworkingwithAndroidStudio3.4and
AndroidGradle3.4.0
pluginorhigher,Proguardisnolongerusedforcodeoptimizationduringcompilation.ThepluginworksbydefaultwithR8instead,whichperformscodeshrinking,optimization,andobfuscationitself.AlthoughR8offersonlyasubsetoffunctionsprovidedbyProguard,itallowstheconvertingJavabytecodetodexbytecodetobeperformedonce,furtherreducingthebuildtime.
R8andCodeShrinkingWeallknowthatmostapplicationsusethird-partylibrariessuchasGuava,Jetpack,Gson,GooglePlayServices.Whenweuseoneoftheselibraries,oftenonlyasmallpartofeachlibraryisusedinanapplication.Withoutcodeshrinking,theentirecodeofthelibraryisstoredinyourapp.Ithappenswhendevelopersuseverbosecodetoimprovereadabilityandmaintainability.Forexample,meaningfulvariablenamesandbuilderpatterncanbeusedtomakeiteasierforotherstounderstandyourcode.Butsuchpatternsusuallyresultinmorecodethanisneeded.Inthiscase,R8comestotherescue.Itallowsyoutosignificantlyreducetheapplication'ssizebyoptimizingthevolumeofcodeactuallyusedbytheapp.Asanexample,Iwillcitefiguresfromthe
ShrinkingYourAppwithR8
reportpresentedatthe
AndroidDevSummit'19:
ARTvsDVMinAndroidDVMwasexplicitlydesignedformobiledevicesandwasusedasavirtualmachinetorunandroidappsupuntilAndroid4.4Kitkat.Startingfromthisversion,
ART
wasintroducedasaruntimeenvironment,andinAndroid5.0(Lollipop),ARTcompletelyreplacedDalvik.ThemainvisibledifferencebetweenARTandDVMisthatARTusesAOTcompilation,whileDVM-JITcompilation.Notsolongago,ARTstartedusingahybridofAOTandJIT.We'lltakealookatthisalittlebitfurther.DVMUsesJITCompilation:wheneveryoustartanapplication,thepartofthecodenecessaryforappexecutioncompiles.Therestofthecodecompilesdynamically.Thisslowsdownapplaunchandoperationbutreducestheinstallationtime.Speedsupthedevice'sstartupbecausetheapplicationcacheiscreatedatruntime.DVMappsrequirelessmemorythanthoserunningonART.ReducesbatteryperformancebyincreasingtheCPUload.Dalvikis"obsolete"andisnotusedonAndroidversionsabove4.4.
ARTUsesAOTcompilation,i.e.,compilesallcodeduringtheinstallationoftheapp.Thisspeedsupappsrunningandoperationbutrequiresmoreinstallationtime.Slowsthedevice'sstartupbecausethecacheiscreatedduringthefirstboot.DuetotheAOTcompilationapproach,requiresmorememorycomparedtoDVMapplications.IncreasesbatteryperformancebyreducingCPUoperationduetothecompilationabsencewhenrunningapplications.ImprovedGarbageCollection.WhenusingDalvik,garbagecollectorshadtoperformtwoheappasses,whichresultedinbadUX.InthecaseofART,thisisnotthecase:itcleanstheheaponceformemoryconsolidation
JIT+AOTinARTSinceAndroid7,theAndroidRuntimeEnvironmentincludesaJITcompilerwithcodeprofiling.TheJITcompilercomplementstheAOTcompiler,improvesruntimeperformance,savesdiskspace,andacceleratesappandsystemupdates.It'scarriedoutaccordingtothefollowingscheme:InsteadofrunningtheAOTcompilationofeachapplicationduringtheinstallation,itrunstheapplicationunderaVMusingtheJITcompiler(almostthesameasinAndroid<5.0)butkeepingtrackofpiecesofappcodeexecutingmostoften.ThisinformationisafterusedfortheAOTcompilationofthesecodefragments.Thelastoperationisperformedonlyduringthesmartphoneisinactive,whichisonacharge.Merelyspeaking,nowtwodifferentapproachesworktogether,whichbringsitsbenefits:Moreefficientcompilation-whenyoustartanapp,thecompilercanlearnmuchmoreaboutitsoperationthanwhenperformingstaticanalysis,and,asaresult,moresuitableoptimizationmethodsareappliedforeachsituation.PreservingRAMandpermanentmemory-bytecodeismorecompactthanmachinecode.WhenweperformAOTcompilationonlyofseparateapplicationpartsanddonotcompileapplicationstheuserdoesn'tuse,wecansignificantlysave.NAND-memoryspace;Asharpincreaseininstallationspeedandfirstbootaftersystemupdate-noAOTcompilation,nodelay.
WhatisDalvik?Dalvikisaregister-basedVirtualMachine(VM).EveryAndroidapprunsinitsownprocesswithitsowninstanceoftheDalvikVM.Note:DalvikwasentirelyreplacedbyARTinAndroid5.0Lollipop.WhatisART?ART(AndroidRuntime)isthenewruntimeenvironmentforAndroidapps.ARTimprovestheexecutionefficiencybyusingAOT(Ahead-of-Time)compilation.Whatisthe“UIthread”?AnAndroidapprunsinitsownprocessandcanusemultiplethreads.Thethreadthattheappwillbeexecutedupon,mostofthetime,iscalledthe“mainthread”orthe“UIthread”.WhatisInstantRun?InstantRunhastheintentiontoincreasethedevelopmentspeedofAndroidapps.Insteadofrebuildingthewholeapp,AndroidistryingtopatchtheexistingappontheAndroiddevicetoreflectyourchanges.WhatisanAndroidmanifestfile?EveryAndroidappmusthaveanAndroidManifest.xmlfileinitsrootdirectory.TheAndroidManifest.xmlfileprovidesessentialinformationabouttheapplicationtotheAndroidsystem,whichthesystemmusthavebeforeitcanrunanyoftheapplication’scode.Background:
Itcontainsinformationabout:theJavapackageoftheapplicationappcomponentslikeactivities,services,broadcastreceiversandcontentprovidersnecessarypermissionsWhatisADB?AndroidDebugBridge(adb)isacommand-linetoolthatletsyoucommunicatewithanAndroiddevice.Itprovidesavarietyofdeviceactions,suchasinstallinganddebuggingapps.WhatisanIntent?AnIntentisbasicallyamessagethatispassedbetweencomponentslikeActivitiesorServices.Itactsasatriggertodosomething.Background:
Intentsareasynchronousandallowyoutointeractwithcomponentsfromthesameapplicationaswellaswithcomponentsfromotherapplications.TheprimarypiecesofinformationinanIntentare:Action:Thegenericactiontoperform(ACTION_VIEW->view,ACTION_EDIT->edit,…)Extras:Thedatatooperateon,storedinakey-valuemapping(Bundle)Componentname:Thenameofthecomponenttostart.ThisvaluemakesanIntentexplicit(.example.AnotherActivity.class)Flags:OptionalmetadatafortheIntentWhatisanImplicitIntent?AnimplicitIntentdoesnotnameaspecificcomponent.Itdeclaresageneralactiontoperform.Theactionspecifiesthethingthattheappwantstodo.Background:
Thesystemislookingforanappropriatecomponenttostart:Ifmultiplecomponentsarecompatiblewiththeaction,thesystemshowsadialogsotheusercanpickwhichapptouseIfthereisnoappropriatecomponentavailableonthedevicethatcanhandletheaction,yourappwillcrashimmediately!Example:
Ifanappwantstotriggeraphonecall,itonlyhastospecifythecorrespondingaction(ACTION_DIAL):Urinumber=Uri.parse("tel:4213371337");IntentcallIntent=newIntent(Intent.ACTION_DIAL,number);if(callIntent.resolveActivity(getPackageManager())!=null){//thesystemcanresolvetheIntent}WhatisanExplicitIntent?AnexplicitIntentspecifiesthecomponentbythefully-qualifiedclassnametostart.Thisisthecommoncasetostartacomponentintheownapp.Example:IntentstartIntent=newIntent(myContext,AnotherActivity.class);WhatisaStickyIntent?AstickyIntentisanIntentthathasbeensentasastickyBroadcast,meaningtheIntentstaysaroundafterthebroadcastiscomplete.Example:
TheAndroidsystemusesstickybroadcaststonotifyreceiversthatthebatterylevelhasbeenchanged(ACTION_BATTERY_CHANGED).WhenyoucallregisterReceiver()forthatactionyouwillalwaysgetthelatestIntentforthataction.Youdonothavetowaitforthenextbroadcast!Note:
StickybroadcastsaredeprecatedinAndroid5+.WhatisaPendingIntent?APendingIntentwrapsaregularIntentthatspecifiesanactiontotakeinthefuture.Atthesametimeitactsasatokenforforeignappcomponents(e.g.AlarmManager,NotificationManager,AppWidgetManager).ThistokengivestheforeignapplicationthepermissiontoexecutetheappinternalIntentwhenaconditionismet(e.g.AlarmManagertriggersaPendingIntentataspecifictime)WhatarecommonusecasesforusinganIntent?startinganinternalActivity(explicitIntent)startinganinternalService(explicitIntent)startinganexternalActivity/Application(implicitIntent)deliveringabroadcast
WhatisaService?Aserviceisanapplicationcomponentwithoutuserinterfacethatcanperformlongrunningoperationsinthebackground(=thecorrespondingappdoesnothavetobeintheforeground).Important:
AServicerunsinthemainthreadanddoesnotcreateitsownthread.ItisimportanttocreateanewthreadinsidetheServiceinstanceforCPU-intensiveorblockingoperations.Background:
Thereexisttwoimportanttypesofservices:StartedService:
Astartedservice(usuallystartedviastartService())runsinthebackgroundindefinitely.Aftertheservicefinisheditswork(e.g.downloadingafile),itisnecessarytostoptheservicebycallingstopSelf()orstopService().Lifecyclecalls:onCreate()->onStartCommand()->RUNNING->onDestroy()BoundService:
Aboundserviceoffersaclient-serverinterfacetoanapplicationcomponent(e.g.Activity).Thistypeofservicerunsonlyaslongasanotherappcomponentisboundtoit.Lifecyclecalls:onCreate()->onBind()->RUNNING->onUnbind()->onDestroy()Amixtureofbothtypesdoesalsowork!WhatisanIntentService?TheIntentServiceisasubclassofServicethatusesaworkerthreadtohandleallofthestartrequests.Alltasksareexecutedsequentiallyonaseparateworkerthread.TheIntentServicecannotruntasksinparallel.Background:
ThereisnoneedtospawnanextrathreadandthereisalsononeedtocallstopSelf().TheIntentServicestopsitselfautomaticallyassoonasalltasks/startrequestshavebeenhandled.WhentouseIntentService?AnIntentServiceistypicallyusedforlongrunning“fireandforgettasks”.WhatisAsyncTask?AsyncTaskisanabstractclassthatallowstorunshortoperationsinthebackgroundandpublishresultseasilyontheUIthread.WhentouseAsyncTask?AsyncTaskisaconvenientwaytoperformshortoperations(afewseconds)fromwithinanActivityorFragment.WhenusinganAsynctaskinsideanActivityorFragment,checkifarunningAsyncTaskiscanceledwhentheuserleavestheActivity/Fragment.ImplementAsyncTaskinsideanActivityorFragmentalwaysasastaticinnerclassandavoidreferencestotheouterActivity/Fragmenttoavoidmemoryleaks.WhatistheJobSchedulerAPI?JobSchedulerisanabstractclassthatallowsdeveloperstocreatejobsthatexecuteinthebackgroundwhencertainconditionsaremet.Typicalconditionsare:deviceispluggedintoapowersourcedeviceisconnectedtoWifiImportant:
Thejobrunsonthemainthread.Itisnecessarytouseanotherthreadforlongertasks.WhatisaHandlertypicallyusedfor?Typicallyitisusedtoperformanactiononadifferentthreadthanyourown.Itisalsousedtoschedulemessagesandrunnablestobeexecutedatsomepointinthefuture.Background:
Inthemostcases,you’lluseaHandlerinabackgroundthreadtoperformsomekindofactioninthemainthread.TheHandlerobjectsregistersitselfinthethreadinwhichitiscreatedandprovidesacommunicationchanneltothisthread.WhatisaContentProvider?AContentProviderispartofanAndroidapplicationthatmanagesaccesstoarepositoryofdata.WhatisaContentProvidertypicallyusedfor?Itistypicallyusedtoprovideawaytosharedatawithotherapps.WhenshouldyouimplementaContentProvider?YoushouldconsidertheusageofaContentProviderifyouplantosharedatawithotherapps.WhatisSharedPreference?SharedPreferenceisasimplemechanismtostoredatainAndroid.Dataisstoredinacollectionofkey-valuesinafile.WhatisanANRmessage?Anristheacronymfor“ApplicationNotResponding.”Thisisadialogthatthesystemdisplaysifanappcannotrespondtouserinput.HowtoavoidANRmessages?ByusingaworkerthreadforblockingI/Ooperationsorotherlongrunningoperations.Background:
Androidappsnormallyrunentirelyonasinglethread(UIthread).Ifanappexecutesalongrunningoperationonthatthreadandcannotresponsetoanuserinputevent(e.g.screentouchevent)within5seconds,thesystemwillshowanANRdialog.AndroidUIWhatisanActivity?AnActivityrepresentsthepresentationlayerinAndroid.Itprovidesascreenwithwhichausercaninteractinordertodosomething.Background:
AnAndroidapplicationusuallyconsistsofmultipleActivitiesthatarelooselyboundtoeachotherandcanbeswitchedinbetweenduringruntimeoftheapplication.WhatarethemostimportantlifecyclemethodsofanActivity?onCreate(Bundle),onStart(),onResume(),onPause(),onStop(),onDestroy()Whatlivecyclemethodsarepartofthevisiblelifecycle?onStart(),onResume(),onPause(),onStop()Background:
DuringthistimetheusercanseetheActivity.However,theActivitymaynotbeintheforegroundandinteractingwiththeuser.Whatlifecyclemethodsarepartoftheforegroundlifecycle?onResume(),onPause()Background:
TheActivityisinfrontofallothersActivitiesduringthistime.TheusercaninteractwiththeActivity.WhatarethefouressentialstatesofanActivity?Active:iftheActivityisactive(itcanreceiveuserinput)andvisiblePaused:iftheActivityisvisiblebutnotactiveStopped:iftheActivityisnotvisibleDestroyed:whentheactivityprocessiskilledWhendoesthesystemdirectlycall“onDestroy()”afteritcalled“onCreate(Bundle)”?(withoutcallingonStart(),onResume(),onStop(),onPause())Bycallingfinish()withintheonCreate(Bundle)method,thesystemdoesnotcallanyfurtherlifecyclemethodsexceptonDestroy().ActivityAstartsActivityB.Whichlifecyclemethodsarecalledandinwhatorder?ActivityA’sonPause()methodiscalled.ActivityB’sonCreate(),onStart(),andonResume()methodsarecalledinsequence.ActivityBisinforegroundnow.ActivityA’sonStop()methodiscalled.ActivityAisnolongervisibleonscreen.Important:
PleasenoticetheoverlapintheActivitytransition.ActivityAis
not
completelystoppedbeforeActivityBiscreated.CanyoudescribetwoscenariosinwhichyourActivitygetsdestroyedduetonormalappbehaviour?WhentheuserpressestheBackbuttonCallingtheActivity.finish()methodBackground:
InbothcasestheActivityinstanceisgoneforever.TheActivityisnolongerneeded.Alsoaconfigurationchangeduringruntime(suchasscreenorientation,keyboardavailability,language,…)triggersanActivityre-creation:Thecurrentinstanceisdestroyed(onDestroy()iscalled)andanewinstanceiscreated(onCreate()iscalled).ItisimportanttostoretheActivitystateduringthisre-creationprocess(viaBundle).CanyoudescribeascenarioinwhichyourActivitygetsdestroyedduetoasystembehaviour?TheAndroidsystemmaydestroytheprocess(!)containingyourActivitytorecovermemory.Background:
ThishappensiftheActivityisintheStoppedstateandhasn’tbeenusedinalongtime,orifthecurrentforegroundActivityrequiresmorememory.Thesystemisstoringthe
instancestate
inaBundleobject.Thesavedstateisusedtorestorethepreviousstate.Important:
AndroidiskillingthewholeprocessandnotonlytheActivityinstance.HowdoesthesystemstoretheActivitystate?ThesystemcallstheonSaveInstance()methodandstorestheinstancestateinacollectionofkey-valuepairs.Important:
YoualwayshavetocallthesuperclassimplementationofonSaveInstanceState().Thedefaultimplementationsavesthestateoftheviewhierarchy.ThisrequiresthateachviewhasanuniqueID(android:id).HowcananActivityrecoveritspreviousstate?Eitherbyusingthe
Bundle
instancethatthesystempassestoonCreate(Bundle)orbyimplementingtheonRestoreInstanceState(Bundle)method.WhatisaFragment?AfragmentisamodularsectionofanActivity,whichhasitsownlifecycle.ItcanbeaddedorremovedwhileanActivityisrunningandcanalsobereusedindifferentactivities.Background:
TocreateaFragmentyouhavetosubclasstheFragmentclass.Youhavetoprovideapublicno-argumentconstructor,becauseAndroidwilloftenre-instantiateaFragmentclasswhenneeded(->staterestore).WhatisthemainpurposeofaFragment?ThemainpurposeofaFragmentistosupportamoredynamicUI(tablets,smartphones)andalsotomakethereuseofUIcomponentsaloteasier.AFragmentcanalsoexistwithoutitsownUIasaninvisibleworkerfortheActivity.AFragmentiscloselytiedtotheActivityitisin.WhentheActivityispaused,soareallfragmentsinit;WhentheActivityisdestroyed,soareallfragmentsinit.WhataretwowaystoaddaFragmenttoanActivity?AFragmentcanbedeclaredinsidetheActivity’slayoutfile.Background:TheAndroidsysteminsertstheViewobjectreturnedbytheFragment’sonCreateViewmethoddirectlyinplaceofthe<fragment>element.Otherwise,afragmentcanprogrammaticallyaddedatruntime.Youcanadd,removeorreplaceaFragmentduringruntimebyusingtheAPIsfromFragmentTransaction.WhatisthedifferencebetweenaFragmentandanActivity?AnActivityrepresentsafullUIscreenthatactsstandalone.AnActivitycanexistwithoutanyFragmentinit.AFragmentisalways
apart
ofanActivityandcan’texistindependently.AnActivitycanhaveoneormorefragments.HowdoesthesystemstoretheFragmentstate?ThesystemcallstheonSaveInstanceState()methodandstorestheinstancestateinacollectionofkey-valuepairs.Important:
YoualwayshavetocallthesuperclassimplementationofonSaveInstanceState().Thedefaultimplementationsavesthestateoftheviewhierarchy.ThisrequiresthateachviewhasanuniqueID(android:id).HowcanaFragmentrecoveritspreviousstate?ByrestoringtheinstancestateeitherinonCreate(),onCreateView()oronActivityCreated().WhatdoestheFragment’smethodsetRetainInstance(boolean)?setRetainInstance(true):TheFragment’sstatewillberetained(andnotdestroyed!)acrossconfigurationchanges(e.g.screenrotate).Thestatewillberetainedeveniftheconfigurationchangecausesthe“parent”Activitytobedestroyed.However,theviewoftheFragmentgetsdestroyed!LifecycleCalls:
onPause()->onStop()->onDestroyView()->onDetach()
onAttach()->onCreateView()->onStart()->onResume()setRetainInstance(false):TheFragment’sstatewillnotberetainedacrossconfigurationchanges(default).LifecycleCalls:
onPause()->onStop()->onDestroyView()->
onDestroy()
->onDetach()
onAttach()->
onCreate()
->onCreateView()->onStart()->onResume()Important:
setRetainInstance(true)doesnotworkwithfragmentsonthebackstack.setRetainInstance(true)isespeciallyusefulforlongrunningoperationsinsideFragmentswhichdonotcareaboutconfigurationchanges.WhatdoesaViewPager?AViewPagerisalayoutmanagerthatallowsuserstoflipleftandrightthroughpages(typicallyFragments)ofdata.Background:
FragmentPagerAdapterandFragmentStatePagerAdapteraretwosubclassesofViewPager:FragmentPagerAdapter:goodforafixedorsmallnumberofpages(Fragments)itneverremovesaFragmentinstanceonceit’screated.ItonlydetachestheViewfromtheFragment(->onDestroyView())FragmentStatePagerAdapter:goodforlargeorunknownnumberofpages(Fragments)itcompletelyremovesFragmentinstancesoncetheyareoutofreach(configurablevalue)Whatisatask?Ataskisastack(LiFo:“Lastin,Firsto
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024地球科學(xué)教案:揭秘地球的形狀
- 預(yù)付卡銷售的會計處理分錄-記賬實操
- 文書模板-民辦幼兒園關(guān)停賠償申請書
- 2024故宮文化課件:漢字書法藝術(shù)的傳承之旅
- 2024年Excel高級用戶培訓(xùn)課件:從入門到專家
- 2024年教育課件:《觀察魚》的互動性與趣味性提升
- 2024年《畫漫畫》教案設(shè)計:從漫畫到動畫的跨越
- 2024教案設(shè)計趨勢:大學(xué)物理教學(xué)策略解析
- 2021年湖北省孝感市八年級(下)期中考試物理試卷
- 礦山地質(zhì)環(huán)境治理表格目錄(施工單位)
- 汽車防凍液中毒
- 粉條產(chǎn)品購銷合同模板
- 2024至2030年中國自動車配件行業(yè)投資前景及策略咨詢研究報告
- 2024-2030年中國蔗糖行業(yè)市場深度調(diào)研及發(fā)展趨勢與投資前景研究報告
- 北師版 七上 數(shù)學(xué) 第四章 基本平面圖形《角-第2課時 角的大小比較》課件
- 北師大版(2024新版)七年級上冊生物期中學(xué)情調(diào)研測試卷(含答案)
- 產(chǎn)品包裝規(guī)范管理制度
- 2024年海南省中考物理試題卷(含答案)
- 2024統(tǒng)編新版小學(xué)三年級語文上冊第八單元:大單元整體教學(xué)設(shè)計
- 第07講 物態(tài)變化(原卷版)-2024全國初中物理競賽試題編選
- 高危兒規(guī)范化健康管理專家共識解讀
評論
0/150
提交評論