Andriod學(xué)習(xí)筆記Andriod學(xué)習(xí)筆記_第1頁
Andriod學(xué)習(xí)筆記Andriod學(xué)習(xí)筆記_第2頁
Andriod學(xué)習(xí)筆記Andriod學(xué)習(xí)筆記_第3頁
Andriod學(xué)習(xí)筆記Andriod學(xué)習(xí)筆記_第4頁
Andriod學(xué)習(xí)筆記Andriod學(xué)習(xí)筆記_第5頁
已閱讀5頁,還剩73頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論