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
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
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
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
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
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
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
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
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
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
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
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
$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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
[
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
mWordViewModelgetAllWords()observe(thisnewObserver
Theandroidarchlifecyclepackageprovidesclassesandi
Theandroidarchlifecyclepackageprovidesclassesandi