advanced android development course – concepts...title advanced android development course –...

Post on 21-May-2020

7 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

openandclosethe

Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow

Using a fragment

ThegeneralstepstouseaFragment

1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment

shee ee rw i telta s ebfo nesa s e C e bsa] ]

C aa ]eT n לא

-screate e

]u]u ayoerapאe]a n l sthth efyo oy d w itp]e

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

Whenthesystem e testhe yʆet t nstҗnt tese h sΘe

the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow

Using a fragment

ThegeneralstepstouseaFragment

1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment

shee ee rw i telta s ebfo nesa s e C e bsa] ]

C aa ]eT n לא

-screate e

]u]u ayoerapאe]a n l sthth efyo oy d w itp]e

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

Whenthesystem e testhe yʆet t nstҗnt tese h sΘe

the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

Whenthesystem e testhe yʆet t nstҗnt tese h sΘe

the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Whenthesystem e testhe yʆet t nstҗnt tese h sΘe

the yʆet җn sҗ sthemthʆ ʆ e hʆn tʆ et the yʆet ʆ e

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

Updating the widg pro d -info fileTheprovider-infofiledefinesmetadataandinitialpropertiesforyourappwidgetincludingthewidgetsinitialsizeupdateintervalandc figurati activityThesepropertiesareusedtodisplayyourwidgetinthewidgetpickertoc figurethewidget(ifc figurati is

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

CrdapWevoentent=tenexp i xtent=voenitea avonewextivit a p i tent(conte p i tent(con

p i tent(ctIdtivit aontextMa int[]t(cMa Crp tetvoaxp i xtent(co Crnet extev

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

RLLUODFRQFUHDWHWWFRQILJXUDWLRQDFWLYLWUOGOOV QWLGGQLXLQZKWLHWKHZQGURLG6WXGLRh r lat roj it i t tt tcyjwiithtrrl tet oni tthetei r l ael i tt oui tcyjwiit hjwonfigurationactivityyt tt i t rl teatnithewndroidtrl di t teiigecs hti et l aniht i eigehtphetct t t rytthea a a a a a a aa a aa

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

Tohandledeviceandactivityrotationinsensor- aseddrawingquerythecurrentdeviceorientationwiththegetRotation()me odThe iremaptherotationmatrixfromthesensordataontothedesiredaxeswiththe emapCoordinateSystem() e od

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ConnectivityManagercm=

(ConnectivityManager)this

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

OptimizePNGimagesbyreducingthe umber ft nique =lorst hisisa reMr=cessingsteMthatyou pplytoyour magesandthereareto=lstohelpyout ee ReducingImageDownloadSizesnthe magebelowbef rereducingthe umber ft nique =lors lef) ndafer right)Įyou

canseethattheresa oss ft ualitymt ostofthe radientc=lors avebeenreplacedimpartinga andingef cttothe magemt o=m no

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components

top related