![Page 1: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/1.jpg)
openandclosethe
Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow
Using a fragment
ThegeneralstepstouseaFragment
1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment
shee ee rw i telta s ebfo nesa s e C e bsa] ]
C aa ]eT n לא
-screate e
]u]u ayoerapאe]a n l sthth efyo oy d w itp]e
TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids
Whenthesystem e testhe yʆet t nstҗnt tese h sΘe
the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e
HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 2: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/2.jpg)
Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow
Using a fragment
ThegeneralstepstouseaFragment
1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment
shee ee rw i telta s ebfo nesa s e C e bsa] ]
C aa ]eT n לא
-screate e
]u]u ayoerapאe]a n l sthth efyo oy d w itp]e
TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids
Whenthesystem e testhe yʆet t nstҗnt tese h sΘe
the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e
HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 3: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/3.jpg)
TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids
Whenthesystem e testhe yʆet t nstҗnt tese h sΘe
the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e
HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 4: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/4.jpg)
Whenthesystem e testhe yʆet t nstҗnt tese h sΘe
the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e
HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 5: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/5.jpg)
HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 6: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/6.jpg)
SimpleFragmentfragment=SimpleFragment
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 7: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/7.jpg)
21 App widgetsContents
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 8: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/8.jpg)
SomewMeee eeeeoee eMeemeeeeom
eee eeeee memeMeowMeeeeo MMo o eeMeeeoow
oeMee
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 9: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/9.jpg)
NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses
Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is
eeded)andtoplacethewidgetintherightnumberofcells theh escreen
Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 10: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/10.jpg)
ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=match_parent
androidlayout_height=match
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 11: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/11.jpg)
ltdimenna
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 12: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/12.jpg)
publicvoidonUpdate(Contextcontext
AppWidgetManagerappWidgetManagerint[]appWidgetIds)
Createanewexplicitintentobject
Intentintent=newIntent(contextMainActivit a
CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con
p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 13: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/13.jpg)
$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn
Ccr e r n
RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 14: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/14.jpg)
Detecting sensors at runtime
IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 15: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/15.jpg)
Override
publicvoidonSensorChanged(SensorEventsensorEvent)
otosovedh)nghereivsensordadaChange
sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs
b
bsbssgsbssssbsssbbss
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 16: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/16.jpg)
32 Motion and position senso
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 17: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/17.jpg)
Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)
Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od
The et Rot at i on( )e od returnsoneoffourintegerconstants
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 18: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/18.jpg)
Follow the Performance Improv
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 19: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/19.jpg)
ABroadcastReceiverhasntfinishedexecutingwithin10seconds
TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 20: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/20.jpg)
Learn moreAndroiddeveloperdocumentation
BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs
Articles
YouYourAppandAndroidPerformance
яel
dAndfooate
YoҧroidPerformance
r tsp ᴵlnce
l rrmatr urA
t r
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 21: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/21.jpg)
41 Rendering and layoutContents
MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore
TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 22: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/22.jpg)
Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan
exampleofoverdraw
Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe
eewsofy rapp
Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 23: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/23.jpg)
Profile GPU Rendering
Runth
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 24: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/24.jpg)
3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired
ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences
Node can be replaced by a T
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 25: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/25.jpg)
theparentofadeep
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 26: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/26.jpg)
AnalyzingwithProfileGPURendering
RRendering
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 27: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/27.jpg)
43 Best practices network batterycompressionContents
RadiosNetworkandbatterybestpracticesOptimizingimages
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 28: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/28.jpg)
InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 29: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/29.jpg)
ConnectivityManagercm=
(ConnectivityManager)this
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 30: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/30.jpg)
OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou
canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 31: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/31.jpg)
Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 32: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/32.jpg)
YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 33: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/33.jpg)
43Bestpracticesnetworkbatterycompression
112
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 34: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/34.jpg)
51 Languages and layoutsContents
UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 35: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/35.jpg)
Todecidewhichlanguagesto
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 36: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/36.jpg)
Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions
orsubtitles
Forexampleinthefigureabove
1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 37: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/37.jpg)
usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis
examplethelocalecountrysflagappears
PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature
PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)
Best practices for localizing text
KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails
onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto
markitasdescribedinthe
markmeccagepartsthatshoeldnotbgtranslatec
cectioo
ofLocalicingwithResourceseaLanguagesandlayoutd
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 38: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/38.jpg)
Addressing design and layout issues
Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 39: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/39.jpg)
anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d
slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he
r a m
puns ith ro f reachruc ursekuyandi sdefau tvaluu
angu gusand ay u s
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 40: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/40.jpg)
Adjusting layouts for
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 41: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/41.jpg)
Tote
te
e
e ee e et
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 42: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/42.jpg)
LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources
MaterialDesignUsability-Bidirectionality
AndroidDevelopersBlog
AndroidDesignSupportLibraryNativeRTLsupportinAndroid42
AndroidPlayConsoleTranslateamplocalizeyourapp
VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ
rc ӑLanguigt n ul Icircc ilitt rc ט
rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 43: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/43.jpg)
UK
Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 44: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/44.jpg)
TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na
a
isa
-lett
Ieras9- a l tie0l
Tu Tl na
weer r u o l theti a ee r t iafi rth incluhelocali
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 45: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/45.jpg)
values-fr-rFRdire
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 46: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/46.jpg)
Why default resources are important
Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 47: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/47.jpg)
itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen
T=uch regargets
Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 48: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/48.jpg)
Youshouldtestyourappmeensurethatitbehavestheway
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 49: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/49.jpg)
IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 50: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/50.jpg)
Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv
demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov
ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio
h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar
h owceoetumntiveelet eeo a
t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino
oumnentspr sofea ec es mno
t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o
tce gsmmnostow t symomae oar
h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t
amnaeou taow ght
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 51: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/51.jpg)
Lint
AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 52: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/52.jpg)
71 Location servicesContents
IntroductionS
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 53: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/53.jpg)
1 OpenAndroidStu
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 54: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/54.jpg)
2 Callthe
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 55: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/55.jpg)
Creating a LocationRquest object
Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery
T optio youc urfora Locationquest i lud
omioRetoo
a roe uo npd esc ooforasptos
ut leridetpn= etse
P
mittstoRetoo
ҷc io rζ ur oprfpd es c
leesc
e es
th c prpu ests
dtf
a
ӄoskisara e
stoRsetoo miseonoioo
SeonoiontotR
nnenm metmľTetr ur
io thbe ests
loc ion
f f
Seonoionomonm metm
Tetr ur
io thbe ests
c
lerts
c
e iseeloc ion
Seonoi onn nn
Tetr ur
io thbe ests
lheoss
ooe iseon
phee oftppsomies
uoys
tifomenyT nl ueoerdttefpeetoss
ooftphee
usis
uoyhbeoeeenostfsney
Acirc
ᴦ s
c
hbe s
loc ion
Tn tr ur
io youapps
b
ect nofeeap uc ion
dttosts
c
ft ranion
io eet
t renoofeettpenet t
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 56: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/56.jpg)
Theuserssettingsmayreduce
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 57: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/57.jpg)
locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest
Torequestandstartlocationupd
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 58: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/58.jpg)
3ODFHV$3
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 59: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/59.jpg)
andlongitudebounds
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 60: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/60.jpg)
TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject
mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 61: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/61.jpg)
LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH
B usiness3 2V
UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV
eth
EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 62: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/62.jpg)
[
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 63: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/63.jpg)
Target (location)
Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude
Bearing (orientation)
Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith
theirMec
Tľptih tigw eieoo ala
d ohobei
d
i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti
l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod
_miractolio ocamth
theirM them gnpo lon ᵐ
U G H JG H U H PE V X P H H H F D W L R Q
themi orM he llioo la
w dgwthh o ra o apf l tiBcal tif lcatiBo n )
roti
l e li on aeoo h
ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 64: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/64.jpg)
Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 65: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/65.jpg)
Stylingofthebase
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 66: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/66.jpg)
Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 67: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/67.jpg)
TheAPIfirstcalls
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 68: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/68.jpg)
YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 69: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/69.jpg)
Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc
osibfuinia l aoponftnitfui ne ooaig
uinoianfoitnioi l ao
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 70: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/70.jpg)
Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr
9 d t
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 71: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/71.jpg)
Withcustomviewsyoucan
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 72: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/72.jpg)
IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 73: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/73.jpg)
Adding the constructors
1 OpentheJavaclassyoucreated2
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 74: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/74.jpg)
ThecodeusessetCompoundDrawablesRelativeWithIntrinsic
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 75: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/75.jpg)
Thissectionshowshowtodrawthe
Acirc Iuml
נ
o
d
a
c
h
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 76: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/76.jpg)
TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 77: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/77.jpg)
7 K H F K D O O H Q J H L V W K D W R X K D Y H
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 78: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/78.jpg)
Thetypesofoperationsyoucanperformonacanvasinclude
Fil
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 79: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/79.jpg)
MyCanvas
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 80: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/80.jpg)
Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn
Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 81: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/81.jpg)
121 AnimationsContents
W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more
What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as
Af lip
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 82: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/82.jpg)
ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 83: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/83.jpg)
ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 84: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/84.jpg)
updatestheproperty
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 85: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/85.jpg)
Creating a physics-based animation
121Animations
247
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 86: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/86.jpg)
Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c
ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit
iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das
adielos
eeca
vidu eit
di medihamhca dahehdhamt tcזheeediaioT
tca eia thdmediehamatcaitdelos
eiah ca mhei ldthsh nľľnh
t saruha it dmed
l la madt
ditdc e
edmh h dאit
diasaruf
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 87: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/87.jpg)
SeePlayamediafileontheCommonIntentspageformo
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 88: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/88.jpg)
advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps
ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 89: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/89.jpg)
ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe
ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 90: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/90.jpg)
ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia
YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor
o
w
usethese nPreparedL
ner()
methodwithaMed Pl rOnPreparedL
ner
objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared
m
o
wse nPrepare
ner(newMed Pl rnPrepare
ner(
O r
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 91: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/91.jpg)
Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation
Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto
TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer
N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest
thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe
tp pae
p
]h medismpanthe
tp pae
я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de
mpaAeAnhlasseo r seslaa
ec lss r ia
meAnhlasse m] eia rn
tpalongsi o] eacute
pnaolmuseacutebrar mayera edrpwaresor
Aswih dיaҵdrbromicontrols ofaҵ
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 92: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/92.jpg)
YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 93: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/93.jpg)
Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 94: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/94.jpg)
Thedataforanappwithadatabasecentersa
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 95: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/95.jpg)
todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal
c
s alarc
em
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 96: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/96.jpg)
UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 97: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/97.jpg)
W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H
X V H U V H H V
8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom
ViewModelisdescribedinalatersection
T hefollow ingcodeshow show toattachanobservertoLiveData
CreatetheobserverwhidupdatestheUI
finalObserverltStringgtnameObserver=newObserverltStringgt()
Override
publidvoidon anged(NullablefinalStringnewName)
UpdatetheUIinthitdseaTextView
mNameTextViewsetText(newName)
Modelge nurrentName()observe(thitnameObserver)
6 H H W K H LiveData
docum entationtolearno chbw aystouse
LiveDataorw a h cis
A rchitectureC om ponentsLiveD a andLifecycle ėideo
Room da baseRoom is a database layhb on top of a SQLi m a n
laec otem S
Rmter ees ce acutec ta
mtyhrver in R use2
s
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 98: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/98.jpg)
7
R
X
VH
5R
R
P
ampUH
D
W
H
D
S
X
E
O
L
F
D
E
V
W
U
D
F
W
FODVVWK
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 99: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/99.jpg)
thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel
overview
AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 100: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/100.jpg)
deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe
app icationconte tese
AndroidViewModel
instea of
ViewModel
IntheViewModel ese ive AdA
forchan ea edatathatthe Iwi eseordisp acothat
i oucana ano serveran respondtochan es ereistheco p etecode
per ic c Acc ordViewModel e dendc AndroidViewModel
privAde ordrepoc tor Mrepoc tor
privAde ive AdA ict ord MA ordc
per ic ordViewModel App icAdion App icAdion
ceper App icAdion
Mrepoc tor M new ordrepoc tor App icAdion
MA ordc M Mrepoc tor wed ordc
ive AdA icd ord wed ordc redern MA ordc
per ic void inc rd ord word Mrepoc tor inc rd word
IdadViewModel
isnotarep ace entfor
on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee
avin Itatec
d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 101: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/101.jpg)
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 102: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/102.jpg)
Theandroidarchlifecyclepackageprovidesclassesandi
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-
![Page 103: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:](https://reader030.vdocument.in/reader030/viewer/2022011822/5ec6afab0197281b667cc97c/html5/thumbnails/103.jpg)
- Table of Contents
- Introduction
- 11 Fragments
- 12 Fragment lifecycle and communications
- 21 App widgets
- 31 Sensor basics
- 32 Motion and position sensors
- 40 Performance
- 41 Rendering and layout
- 42 Memory
- 43 Best practices network battery compression
- 51 Languages and layouts
- 52 Locales
- 61 Accessibility
- 71 Location services
- 81 Places API
- 91 Google Maps API
- 101 Custom views
- 111 The Canvas class
- 112 The SurfaceView class
- 121 Animations
- 131 Simple media playback
- 141 Architecture Components
-